beta.blog

Programming

JavaScript: Recurring setTimeout()

by on Aug.02, 2013, under Programming

I wondered how to create a recurring setTimeout in JavaScript. After doing several attempts with setTimeout implementations which would simply call themself, I came to the point, it would be smarter to look up for an easier and more clean solution instead. It turned out there is a function in JS which is similar to setTimeout but behaves slightly different. The similar function is called setInterval and it behaves pretty much the same way setTimeout does, it however gets executed recurringly.

Here’s an example:

setInterval(function () {
  alert("Hello world!");
}, 2000);

So what it does is it executes the alert instruction whenever 2000 milliseconds (2 seconds) have passed. The slight but important difference is:

setTimeout(function, 2000): executes the function after 2000 milliseconds have passed
setInterval(function, 2000): executes the function after 2000 milliseconds have passed recurringly.

Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!