Introduction
This article is about delayed execution for a function that we can have in setInterval.
We all know, if we want to execute a function or run a task after certain interval of time then we can schedule a call. This can be done in two ways:
- setTimeout which allows us to run a function once after the interval of time.
- setInterval which allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
Here, we will look into how we can delay a function execution in setInterval() and see how it behaves.
setInterval
The setInterval method has the same syntax as setTimeout:
let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)
All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.
Let us consider this snippet:
let i = 1;
function test(value){
console.log("received value is : ",value);
}
setInterval(function() {
test(i++);
}, 2000);
Observe the output:
//Output:
received value is : 1
received value is : 2
received value is : 3 and so on...
It prints the message after 2 seconds continuously.
It is possible that execution of test function turns out to be longer than we expected and takes more than 2000ms.
what will happen in such case?
let i = 1;
function test(value){
setTimeout(function(){
console.log("received value is : ",value)
},5000);
}
setInterval(function(){
test(i++)
},2000);
I am adding a setTimeout() with a delay of 5000ms which exceeds the interval specified in setInterval().
If you notice the output in your browser console, you would notice the output
received value is : 1
after a delay of 7000ms.
And then you could see the following in an interval of 2000ms
received value is : 2
received value is : 3
received value is : 4
In this case the engine waits for test function to complete, then checks the scheduler and if the time is up, runs it again immediately.
In the edge case, if the function always executes longer than delay ms, then the calls will happen without a pause at all.
Such a case might appear while making an API call inside the function/callback mentioned in setTimeinterval().
Yeah that's about delay in setInterval. Hope this was helpful.
Cheers !!!
Top comments (0)