/

Exploring JavaScript Timers

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
2
3
4
5
6
7
setTimeout(() => {
// This code will run after 2 seconds
}, 2000)

setTimeout(() => {
// This code will run after 50 milliseconds
}, 50)

In the above syntax, you can define a new function or pass an existing function name with additional parameters if needed:

1
2
3
4
5
6
const myFunction = (firstParam, secondParam) => {
// Perform some actions
}

// This code will run after 2 seconds
setTimeout(myFunction, 2000, firstParam, secondParam)

Additionally, setTimeout returns a timer ID which you can use to clear the scheduled function execution if needed:

1
2
3
4
5
6
const id = setTimeout(() => {
// This code should run after 2 seconds
}, 2000)

// I changed my mind, cancel the scheduled execution
clearTimeout(id)

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
2
3
4
5
setTimeout(() => {
console.log('after')
}, 0)

console.log('before')

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
2
3
setInterval(() => {
// This code runs every 2 seconds
}, 2000)

To stop the execution of a setInterval function, use the clearInterval method by passing the interval ID returned by setInterval:

1
2
3
4
5
6
const id = setInterval(() => {
// This code runs every 2 seconds
}, 2000)

// Stop the execution
clearInterval(id)

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
2
3
4
5
6
7
const interval = setInterval(() => {
if (App.somethingIWait === 'arrived') {
clearInterval(interval)
return
}
// Perform other actions
}, 100)

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
2
3
4
5
6
7
8
9
const myFunction = () => {
// Perform some actions

setTimeout(myFunction, 1000)
}

setTimeout(() => {
myFunction()
}, 1000)

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”]