Why we use setTimeout() function in Node.js ?
The purpose of setTimeout function is to execute a piece of code after a certain interval of time. The setTimeout() function accepts two arguments. The first argument is a function and the second argument is time in milliseconds. The setTimeout() executes the function passed in the first argument after the time specified in the second argument. The setTimeout function doesn’t block other code and the rest of the code is executed and after a specified time the code inside setTimeout function is executed.
setTimeout( function , time_in_milliseconds )
Example 1: In this example, a function is defined and then that function is passed as the first argument of setTimeout() function. The second argument specifies the time delay in milliseconds which is 3000. Therefore, the code inside the function will execute after 3000 milliseconds, and the rest of the code in the program will be executed.
Explanation: In the above code, the code inside setTimeout() function will be stored and the next statement will be executed. After the call stack is empty and the specified time has passed, the code inside setTimeout() function will be executed. Therefore, the code above displays “Printed immediately”, then waits for 3 seconds, and then “Printed after 3 seconds” is displayed.
Example 2: Another example of setTimeout() function is given below. The example code given below is a tricky one. It is expected that the output will be “Printed immediately” followed by numbers from 1 to 5. But the code doesn’t work like that. The reason for this is because the setTimeout() function stores the code with the references of data used(in this case i) and it will be executed only after the call stack is empty. So, for every iteration of for loop, the setTimeout() function will store the code. The for loop will terminate once becomes equal to 6. After that, the next statement will be executed and then the call stack becomes empty. After the specified time delay, the code inside setTimeout() function will execute. Since the value of i has now become equal to 6, 6 will be displayed every time.
Explanation: In the above code, the for loop executes for values from i=1 to i=5, in every iteration, the code inside setTimeout() function will be stored with the reference of variables used(here i). When the value of i becomes 6, the loop will terminate. Then, the next statement will be executed. After the call stack becomes empty and the specified time for each setTimeout() function passes, the code inside every setTimeout function will execute. Therefore, the code displays ‘Printed immediately’, and then after the pass of every second the value of i is displayed which has now become 6.