DEV Community

Cover image for Timers and schedulers in Javascript
Ajah Chukwuemeka
Ajah Chukwuemeka

Posted on

Timers and schedulers in Javascript

In building programs that would eventually be integrated into our softwares, sometimes, we need to defer the execution of some part of our program with respect to time. Also, we might want to carry out some routine tasks at specific intervals from a given benchmark. In the bid to do this, Javascript developers mostly leverage on the specification of any of the setTimeout or setInterval global functions so as to achieve their aim. In this article, we would do a deep dive as well as experimentation on the use of these timer functions.

First, we would start with the setTimeout function. It is used to schedule a task that would run only once after the event cycle has elapsed after the specified delay. The setTimeout function accepts a function or string as its first argument, a delay time in milliseconds as its second argument and an optional third or more arguments which are supposed to act as the function parameters. However, when the first argument to the setTimeout function is a string, it wraps it into an eval function internally and executes (this throws a TypeError in NodeJS runtime) and when the delay argument is not provided, it assumes that the delay is 0ms. The return value of a setTimeout function is a reference which can be used to clear the timeout before or after it has executed so as to remove it from the event loop.

Typical usage of the setTimeout function

let timeoutId = setTimeout(function(){
console.log(`Isn't Javascript a cute language?`)
}, 2000)

let timeoutId = setTimeout(`console.log('How are you')`)

const greeter = (name, time_of_day) => {
console.log(`Good ${time_of_day}, ${name}`)
}

// then we call the setTimeout function with the greeter function as an argument
let timeoutId = setTimeout(greeter,2000,'Emeka','afternoon')

setTimeout function does have an anti-matter function which is responsible for cancelling and clearing the timeout function from the event loop. This function utilizes the return reference value of the setTimeout function so as to know which timeout function to cancel. It is used as follows:

let timeoutId = setTimeout(function(name){
console.log(`How are you today ${name}?`)
}, 2000, 'Emeka')

clearTimeout(timeoutId)

Since we have exhaustively talked about the use of the setTimeout function, we can now talk about the setInterval function. Its usage is the same as that of the setTimeout function. However, the beauty of it is that it performs an action after every specified delay time in the function call. More like repeatedly performs an action after the specified delay time in milliseconds. This function is good for time repetitive tasks that are time-bound.

Typical usage of the setInterval function

let intervalId = setInterval(function(){
console.log(`Isn't Javascript a cute language?`)
}, 2000)

let intervalId = setInterval(`console.log('How are you')`)

const greeter = (name, time_of_day) => {
console.log(`Good ${time_of_day}, ${name}`)
}
// then we call the setInterval function with the greeter function as an argument
let intervalId = setInterval(greeter,2000,'Emeka','afternoon')

The first call to setInterval executes its assigned function every 2s whereas the second call executes the assigned function like a loop without any delay.

However, as there is a clearTimeout function for canceling setTimeout functions and removing them from the event loop, there is a clearInterval function for removing setInterval functions also. It utilizes the return value of the setInterval call which serves as a reference parameter for it. It is used as follows:

let intervalId = setInterval(function(name){
console.log(`How are you today ${name}?`)
}, 2000, 'Emeka')

clearInterval(intervalId)

In addition to this, in NodeJS there is also another scheduler function called setImmediate which is executed at the end of the turn of the NodeJS event loop. It works like setTimeout function with a 0ms delay value. It also has the clearImmediate anti-matter for cancelling it and garbage collection.It is used thus:

let immediate = setImmediate(function(name){
console.log(`How are you today ${name}?`)
}, 'Emeka')

clearImmediate(immediate)

In NodeJS, the above timer functions do have extra methods that can only be accessed within the NodeJS runtime. These are the ref, hasRef, refresh (for setTimeout only) and unRef methods that can be used with the return value of the functions.

To read more about timers and schedulers in Javascript, please follow the links below. They helped me a bunch. Thank you for your time.

Scheduling Tasks in JavaScript Using setTimeout & setInterval
Scheduling: setTimeout and setInterval
Timers | NodeJS

Top comments (0)