Exploring JavaScript Timers
When writing JavaScript code, there may be instances when you need to delay the execution of a function. In this blog post, we will explore how to effectively use JavaScript timers such as setTimeout
and setInterval
to schedule function execution in the future.
setTimeout()
The setTimeout
function allows you to delay the execution of a function by specifying a callback function and a time value representing the delay in milliseconds. Here’s an example:
1 | setTimeout(() => { |
In the above syntax, you can define a new function or pass an existing function name with additional parameters if needed:
1 | const myFunction = (firstParam, secondParam) => { |
Additionally, setTimeout
returns a timer ID which you can use to clear the scheduled function execution if needed:
1 | const id = setTimeout(() => { |
Zero Delay
You can set a timeout delay of 0
to execute the callback function as soon as possible, but after the current code execution:
1 | setTimeout(() => { |
The above code will output before after
. This can be particularly useful to prevent blocking the CPU during intensive tasks and allow other functions to be executed while performing heavy calculations.
Note: Some browsers, such as IE and Edge, have a
setImmediate()
method that provides similar functionality, but it is not available in other browsers. However, it is a standard function in Node.js.
setInterval()
The setInterval
function is similar to setTimeout
, but instead of running the callback function once, it executes it repeatedly at a specified time interval (in milliseconds):
1 | setInterval(() => { |
To stop the execution of a setInterval
function, use the clearInterval
method by passing the interval ID returned by setInterval
:
1 | const id = setInterval(() => { |
It is common to include the clearInterval
method inside the setInterval
callback function to automatically determine whether the function should continue running or stop. For example, the following code runs a function until App.somethingIWait
has the value of 'arrived'
:
1 | const interval = setInterval(() => { |
Recursive setTimeout
While setInterval
triggers a function every n milliseconds, it does not take into account when the previous function execution finishes. This may lead to overlapping executions, especially if the function’s execution time varies. To avoid this, you can use recursive setTimeout
to schedule a function call after the completion of the callback function:
1 | const myFunction = () => { |
By using recursive setTimeout
, you can achieve a scenario where each function execution is properly sequenced without any overlaps.
Both setTimeout
and setInterval
are available in Node.js through the Timers module. Node.js also provides an equivalent function, setImmediate()
, which is primarily used to work with the Node.js Event Loop.
tags: [“JavaScript Timers”, “setTimeout”, “setInterval”, “recursive setTimeout”]