You are currently viewing 3 Best Points to Know About JavaScript setIntervals Function

3 Best Points to Know About JavaScript setIntervals Function

setInterval JavaScript Example

In this article, we will see How to use setinterval function in javascript with example. Intervals keep running a task forever so you should clear the interval when appropriate. You can do that using the clear interval function.


const intervalId = setInterval(greet, 2000, 'john')

So, capture the return value from set interval and pass it in as an argument to clearInterval.

Main Points:

1. Intervals are not part of JavaScript itself. They are implemented by the browser and setInterval are basically names given to that functionality in javascript.
2. It is possible to achieve the same effect as setInterval with a recursive setTimeout.

recursive setTimeout

setTimeout(function run()){
}, 100)


setInterval(function run() {
  }, 100)

In the above code, we have setInterval with a duration of 100ms. And we have the same functionality with recursive setTimeout. So, basically the run() function keeps calling itself every 100ms. However, there is one difference in these approaches.

1. In the case of recursive setTimeout the same 100ms is guaranteed between executions. The code will log ‘hello’ to the console, and wait 100 milliseconds before it runs again. Irrespective of how long the code takes to run, the interval will remain the same.

setInterval on the other hand works differently in the sense that the duration interval includes the time taken to execute the code you want to run. So, if the first time the code takes 40ms to run the interval is only 60ms and then if the 2nd time the code takes 50ms to run the interval is 50ms.

READ ALSO  How to Create a Button in JavaScript | Easy Way

Typically it shouldn’t affect your code too much but if your code can take longer to run than the time interval itself, it’s always better to go with recursive setTimeout rather than setInterval. This will keep the time interval constant between executions regardless of how long the code takes to execute and also you won’t get any errors.

2. The second difference is that with recursive setTimeout. You can actually calculate a different delay before running each iteration. So, recursive timeout gives you the flexibility of running the same code over and over but with different intervals, whereas setInterval is always a fixed interval duration.

Leave a Reply