Any activity that is planned at a future time interval is generally referred to as scheduling. JavaScript has functions for running at a specified schedule time or interval. They are:

  1. setTimeout(function, milliseconds)
  2. setInterval(function, milliseconds)

Both the functions allow you to execute a piece of JavaScript code/function at a certain point in the future.


Javascript setInterval Vs setTimeout

setTimeout(function, milliseconds)

JavaScript setTimeout() is a function that execute a JavaScript statement after 'X' interval. This means that it is a time based code execution method that will execute a script only one time when the interval is reached. It will not repeat again unless you gear it to loop the script by nesting the setTimeout() object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().



If you want something to happen one time after a specified period of time, then use setTimeout(). That is because it only executes one time when the specified interval is reached.

setInterval(function, milliseconds)

JavaScript setInterval() is a function that execute a JavaScript statement every 'X' interval. This means that it is a time interval based code execution method that has the native ability to repeatedly run a specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().



If you want to loop code for animations or on a clock tick, then use setInterval().

Accuray (setTimeout Vs. setInterval)

Please note that all scheduling methods do not guarantee the exact delay. For example, the in-browser timer may slow down for a lot of reasons:

  1. The CPU is overloaded.
  2. The browser tab is in the background mode.
  3. The laptop is on battery.

Javascript timer

Both, setTimeout and setInterval essentially try to do the same thing, but the setInterval approach will be more accurate than the setTimeout approach, since setTimeout waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms. Although one might think that setInterval will execute exactly every 1000ms, it is important to note that setInterval will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish. The delay is almost always negligible, all that may increase the minimal timer resolution (the minimal delay) to 300ms or even 1000ms depending on the browser and OS-level performance settings.



NEXT.....JavaScript Programming