Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

setTimeout method

Even if you do that: function say(something){ alert(something); } for(let i = 0 ; i < 3 ; i += 1){ window.setTimeout(say,5000,"Hello"); } :the timeout will be setted only for the 1/3 of the loop,That means that when a timeout has been setted, even if we use a loop,the timeout has one use,why?

Am I right?

Yes but the timeout doesn't "restart"?

There are 3 timeouts but only on has ran?

Steven Parker
Steven Parker
243,266 Points

All 3 timeouts ran. That's why you see 3 alerts.

And the repeating is part of what we talked about last week, remember? I said "each one of the 3 timers creates one alert and then it's done. If you want an event to repeat, use setInterval instead of setTimeout."

So setTimeout does not restart, but setInterval does.

It is starting to be clearer but the only thing I don't understand is: When a timeout is over,it is done and for me when it is done it is like if the timeout doesn't exist?

And that means that a timeout isn't necessary a delay?It can be a delay but it can also be other thing that you should know .I talk about the three timers,one is a delay and the two other one aren't "delay".

Steven Parker
Steven Parker
243,266 Points

It's a delay for the callback, but it does not delay the rest of the program. All 3 timers are exactly the same. And yes, when a timeout has called the callback and is done, it is disposed — meaning it does not exist any more.

1 Answer

Steven Parker
Steven Parker
243,266 Points

Loop or not, a timeout timer always has just one use. When the time is over, it calls the callback, and then it is done.

But I'm not sure what you mean by "setted only for the 1/3 of the loop". Could you rephrase that part of the question?

It was just for saying that even if your loop last 3 times, only 1 time will have the timeout.

Steven Parker
Steven Parker
243,266 Points

Remember, we talked about this before, when you noticed that you got 3 alerts, one after the other.

So all 3 times through the loop get a new timeout. That's why you see 3 alerts.

I don't understand why you are meaning by a new timeout because there is one timer that run in total.

Steven Parker
Steven Parker
243,266 Points

No, there are 3 timers, one from each time through the loop. Each timer causes an alert, and that's why you get 3 alerts.