SetTimeout doesn't work

Trying to use a timer to building a game.
The timer doesn’t work and I can’t figure out what I’m doing wrong.
Can someone help, please?:pray:t2:


Are you following the correct syntax?

Please show us code that doesn’t work.

<!DOCTYPE html>
	<div id="number">
			var count = 0;
			function updateCount() {
			count = count + 1;
			document.getElementById("number").innerHTML = count;
			setTimeout(updateCount, 1000);


Sorry, I thought I posted the code too :frowning:

You’ve placed the setTimeout inside the function you’re trying to call :slight_smile:

Sory, moving my first steps with Javascript and following instructions from a book … where should it be placed ?:sweat:

Well, actually I should’ve also asked what’s the desired outcome because the way you’re written will create a neverending loop, but maybe that’s what you wanted :stuck_out_tongue:

I didn’t notice it initially, but the main thing you’re missing is actually calling the function:

function updateCount() { some stuff } // function declaration
updateCount() // function call

Now, back to that loop I mentioned. After you manually call the function, javascript engine will execute it and see that you’re also calling the same function from within, via a setTimeout, so it will execute the function once more, and again see that it has a setTimeout, so it will call it again, and again, and again…
That loop will never end unless you wrap the setTimeout function with an if statement and add some condition.

There is a different (more common) way to keep firing a function and that’s via a setInterval, then your code would look like this:

var count = 0;

function updateCount() {
  count = count + 1;
  document.getElementById("number").innerHTML = count;

setInterval(updateCount, 1000)

Sorry, I had to go to work :frowning:
I figured it out. Basically, I didn’t call the function.
My goal was setting a timer to use for a game where every second 6 people will be shown on-screen.

Thank you so much for your help !!!

1 Like

and yes, I will need if else statement :slight_smile:

I’m curious to see the game, sounds neat!

And I’m actually trying to work on a tutorial, starting from nearly the same code you posted, and building to a whole complex Timer class. I was working on the Pomodoro thing, and rather than building it with a framework, I wanted to try my hand at creating my own component classes. The first I tried was a Timer class.

It’s kind of cool: you can set it to go for a certain duration, and you can trigger events either every second, or at completion. If you include the Timer’s DOM node, you can listen for custom events triggered on that (timer.tick and timer.complete), causing your own events, or you can also pass the Timer handlers for onTick and onComplete.

The tutorial is by no means complete, but if you’d like to see the Timer class code, I’m more than willing to share.