Well, depending on your situation, setTimeout() or setInterval() might come handy. Let’s take a look at the syntax of both the methods.
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.
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:
alert("Set timeout called");
// The above alert will trigger after a delay of 1 seconds
alert("Set interval called");
//The above alert will trigger after every 1 seconds repeatedly until it is cleared.
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 :
//set a time out and assign it to a variable
var myTimer = setTimeout(myfunction, 1000);
//clear the timeout by specifying the ID(variable) assigned to it
//set interval and assign it to a variable
var myInterval = setInterval(myFunction, 5000);
//clear the interval by passing the ID(variable) as a parameter
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.