Quite often you might come across scenarios wherein you would need to have a timer set in JavaScript. For instance, you might want to call a function after a delay of say 10 seconds or you may want to trigger a function every 15 seconds automatically. A very common scenario is to show a popup after a specific or set time.

Well, depending on your situation, setTimeout() or setInterval() might come handy. Let’s take a look at the syntax of both the methods.

setTimeout(expression_to_call, delay);
and
setInterval(expression_to_call, delay);

If you notice, both the methods have same parameters. First parameter is the function/expression to be executed and the second parameter is the delay or interval after which the specified function needs to be called.

What is the difference between setInterval() and setTimeout() in JavaScript?

While both of the methods seem to be similar there is a subtle difference in how they are executed. The setTimeout() function will execute the callback function once after a delay of the time specified, whereas setInterval() will execute the callback function repeatedly after an interval of the delay time specified.

Let’s take a look at an example:

As you can see, when we use setTimeout(), it triggers the callback function after a delay of 1 seconds. You can use setTimeout() to show a popup or overlay after a specific or set time. Whereas you can notice that the setInterval() function will keep calling the callback function after every 1 seconds repeatedly. You can stop the interval by using the clearInterval() method. Similarly you can stop the setTimeout() by using clearTimeout() method. Let’s take a look at an example :

As you can notice, clearing both setTimeout() and setInterval() is similar and easy. Just that you need to remember which one is for what.

You can do a lot using these powerful methods, but please be reasonable when you set setInterval() as keeping a very short interval might sometimes slow down the browser. Also please note that when you use setInterval() method, it doesn’t actually wait for the previous function to be complete before it fires the method next time.

Hope you are clear with the usage of all the four methods mentioned here. Do let us know your comments.