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 PointsPrint into the console hello every 5 second.
I think we should use the set timout but I don't know how to structure my program!
2 Answers
Christof Baumgartner
20,864 PointsThis should do it and be executed when the page loads (in all browsers).
(function(){
var f = function() {
console.log("Hello World");
};
window.setInterval(f, 5000);
f();
})();
Steven Parker
243,266 PointsYes, you can do this with setTimeout.
Christof's example using setInterval is perhaps a technically better approach, but since you asked about setTimeout, here's how you might use it to do the same thing:
function hello() {
console.log("Hello");
window.setTimeout(hello, 5000);
}
hello();
And you might want to save the timeoutID value that either of these functions return, so you can use it later in a call to clearTimeout or clearInterval. Otherwise, you won't be able to stop it without closing the browser tab.
Christof Baumgartner
20,864 PointsJust one comment on setTimeout: The loop can take a little longer than 5000 ms ( eg. 5002 ms) For the very most applications that doesn't matter. The reason is that the code gets executed and then it waits 5000 ms. As the code execution can also take some time (depending on what you want to write there), this gap can add up. The setInterval keeps this 5000ms rythm no matter how long the function needs. This only matters if you really want to keep your exact 5 seconds, or if your code takes a long time to execute.