codedamn logo
codedamn

setTimeout() in Node js

  • Vishnupriya's profile image
    Vishnupriya
    Team codedamn
setTimeout() in Node js

Hey readers! Before we jump to setTimeout in Node js, let’s first understand the whole concept behind it and we will cover some of the most asked questions. 

The setTimeout is a part of timers in Node js. Now the question might arise, what are timers in Node js? The timers module in Node js contains a bunch of functions that execute code after a fixed interval of time. This is possible because of Node js API which provides scheduling the code at a particular instance. setTimeout() is widely used when it comes to testing and is an important element in Node js timers. Developers use this to test server or backend working of an application and to find bugs in the application.

setTimeout()

setTimeout() is used to schedule the execution of the code after a particular amount of time. It is very similar to the function of JavaScript “window.setTimeout()” API. The function accepts a function to be executed as a first argument and the delay of  “no of time” is passed as the second argument. We can also add multiple arguments passed to the function. Here is a code snippet of the theory we’ve done till now:

function myFunction(args) {
console.log(`args was => ${args}`);
}
setTimeout(myFunction, 1700, 'fun');

The above code will run myFunction() after 1700 milliseconds or 1.7 seconds due to the method called setTimeout(). This does not follow the exact time limit but it ensures that the function will at least execute for the time limit declared in the method. It is because other function blocks and event loop running push the execution of the time outback. 

setTimeout() diagram

Output of setTimeout()

setTimeout() gives output as Timeout object that is used for reference of the timeout set. This reference object can be used to clear the timeout by using the clearTimeout() method and to change the behavior of the function. 

Timeout objects that are returned are setInterval and setTimeout. It provides two major functions ref() and unref() intended to augment Timeout behavior. The Timeout method is scheduled using a set of functions on the object. The behavior of the object gets slightly changed when the unref() method of Timeout is used. If the last code is executed then the Timeout object is not called, it will clear the process. Likewise, a Timeout object that has unref() on it can be discarded by calling the ref() method on the same Timeout object. This ensures the proper execution of the code, however, the initial exact behavior is not re-stored for performance reasons.  

Below is the code snippet to depict what we’ve done till now.

const timerObject = setTimeout(() => {
console.log('will i run this code?');
});
/* if kept alone, the statement will keep the above timeout
// fromexecuting the code, because the timeout will be the only thing keeping the //program from exiting one timerObject.unref();
*/ we can bring it back to life by calling ref() inside an immediate
setImmediate(() => {
timerObject.ref();
})

setInterval()

For infinite loop execution, setInterval() is used. It takes a function and delay time as arguments and runs infinite time with the delay given in function. It is similar to setTimeout() where the additional arguments can be passed after a delay which will then pass onto function call. The delay is not fixed just like setTimeout() due to the event loop and is therefore treated as an approximate delay. 

Below is the code snippet for understanding setInterval() better.

function intervalFunction() {
console.log('Infinite loop!');
}
setInterval(intervalFunction, 1700);

In this, the intervalFunction() will execute for about 1700 milliseconds or 1.7 seconds until its stopped. It also returns the Timeout object like the setTimeout() method which can be used as a reference and can be used to modify the set interval. 

How to use clear Timeout?

setTimeout(), setInterval() returns a timer object that is used as a reference of the set Timeout object. Bypassing the set object to the respective clear function, execution of the object returns to waiting. The functions that are used to do this are clearTimeout() and clearInterval().

Below is the code snippet to understand it must better.

const timeoutObject = setTimeout(() => {
console.log('timeout beyond time');
}, 1500);
const intervalObject = setInterval(() => {
console.log('interviewing the interval');
}, 500);
clearTimeout(timeoutObject);
clearInterval(intervalObject);

Let us understand how setTimeout() works using an example. Consider a given code snippet:

for (i = 1; i <= 5; i++){
setTimeout(() => {
console.log(i);
},i*1000)
}
console.log('Hello!');

In the above code snippet, the loop is executing from values in the range 1 to 5. For every iteration, the setTimeout() function will store the reference variable with a given number. When the value of the reference variable (which in our case is ‘i’) is assigned ‘6’, the loop breaks, and the next statement is executed. After the call stack is emptied and the mentioned time for the setTimeout() passes, the code in the function gets executed and the message “Hello!” is printed after which it gives the value of i which is 6. This is how the setTimeout() function in Node js works.

 

User avatar