setTimeout() vs setInterval() in Javascript

s

It feels like it has been a lifetime since my last blog!  I must apologize for the long delay, but between finding the time and finding a good topic to blog about, it’s being difficult.

In today’s article, it’s been a while since I’ve needed to use either the setTimeout or setInterval functions and it seems many people are not familiar with the setInterval function.

Let’s start by describing the two.

setTimeout allows us to tell the user’s browser to perform some Javascript in X milliseconds.  The Javascript executed can be a function call, a single line of Javascript, etc…

For example:

setTimeout(“alert(‘Hello, World!’)”, 5000);

The above example will create an alert box with the message “Hello, World!” after 5 seconds.

setInterval is very similar to the above, the key difference is that it repeatedly runs the same Javascript at the specified time.

For example:

setInterval(“alert(‘Hello, World!’)”, 5000);

The above example will create an alert box with the message “Hello, World!” EVERY 5 seconds.

So, when should you use setTimeout and when should you use setInterval?  Well, the answer is quite simple, if you just want to execute the code once, use setTimeout.  If you want to execute the code repeatively, use setInterval.

No more setTimeout’s that call a function and inside of that function another setTimeout call!

About the author

By Jamie

My Books