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
Vic Mercier
3,276 PointsI don't understand how this code run.Please explain it everything loop,setTimeout. Go step by step.
function say(s){ alert(s); } for(let i = 0; i < 3 ; i += 1){ window.setTimeout(say,5000,"Hi"); }
Vic Mercier
3,276 PointsTo summarize our big discution,when a timeout has been setted, it is just for once .It is like if we can erase it from our code,arent?
Steven Parker
243,266 PointsBut if you erase it from the code, it won't even happen one time.
As the code is now, each of 3 timers will happen just once (for a total of 3 alerts).
Vic Mercier
3,276 PointsWhat is the usefulness to clear a timeout?
Steven Parker
243,266 PointsDo you mean why would you want to clear a timeout? Here's one possible scenario: you start a process that should take less than a minute, and also start a timeout to display a warning message 1 minute later in case the process is still running. But in 30 seconds the process finishes, so at that time you cancel the timeout.
Vic Mercier
3,276 PointsWrite code to explain your last answer clearer please.
Steven Parker
243,266 PointsThat was just an imaginary scenario to convey an idea about when you might use clearTimeout. Specific information about the process being monitored would be needed to actually write the code.
1 Answer
Steven Parker
243,266 PointsSo here's a breakdown:
function say(s) { create a function named "say" with 1 parameter
alert(s); make an alert box showing the value passed in
}
for (let i = 0; i < 3; i += 1) { do the following 3 times
window.setTimeout(say, 5000, "Hi"); wait 5 seconds and then call:
say("Hi")
}
Essentially, when this program runs, then 5 seconds later you should get 3 alerts saying "Hi", one after the other.
Vic Mercier
3,276 PointsWhy do I get 3 alerts saying "Hi", one after the other?Why the timeout doesn't restart?
And a timeout has "one use"?Aren't
Steven Parker
243,266 PointsEvery call to setTimeout generates a new timer. They all run concurrently.
Steven Parker
243,266 PointsYes, 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.
Vic Mercier
3,276 PointsVic Mercier
3,276 PointsEvery timeout has one use?