We can delay a function call in JavaScript through scheduling, which allows us to execute the function at a certain time later.
There are two methods to get this done:
- setTimeout - execute a function once after certain time (in milliseconds)
- setInterval - execute a function repeatedly at the provided interval of time (in milliseconds)
Example - setTimeout with 5 seconds
delay() {
console.log('Regular call.');
let delayTimer = setTimeout(() => { console.log('Delayed call.') }, 5000);
}
Example - setInterval with 5 seconds
delay() {
console.log('Regular call.');
let delayInterval = setInterval(() => { console.log('Delayed call.') }, 5000);
}
We can use the following methods to cancel the setTimeout and setInterval:
- clearTimeout - clears the timeout set by setTimeout()
- clearInterval - clears the interval set by setInterval()
Example - clearTimeout
delay() {
console.log('Regular call.');
let delayTimer = setTimeout(() => { console.log('Delayed call.') }, 5000);
clearTimeout(delayTimer); // Cancels the delayTimer
}
Example - clearInterval
delay() {
console.log('Regular call.');
let delayInterval = setInterval(() => { console.log('Delayed call.') }, 5000);
clearInterval(delayInterval); // Cancels the delayInterval
}
Keep in mind!
- The default delay is 0 second
- 1000 ms = 1 second