Why we use setTimeout() function in Node.js ?
Last Updated :
02 Jul, 2024
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.
JavaScript setTimeout() Method
This method executes a function, after waiting a specified number of milliseconds. 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.
Syntax:
window.setTimeout(function, milliseconds);
Parameter:
- function: the first parameter is a function to be executed
- milliseconds: which indicates the number of milliseconds before the execution takes place.
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.
JavaScript
printStatement = () => {
console.log('Printed after 3 seconds');
}
setTimeout(printStatement, 3000);
console.log('Printed Immediately');
Output:
Printed Immediately
Printed after 3 seconds
Explanation: In the above code, setTimeout
stores the code, executes the next statement, and after the call stack is empty and time has passed, displays "Printed immediately", then "Printed after 3 seconds"
Example 2: This example shows how setTimeout
delays execution. It is expecting numbers 1 to 5, it logs 6 repeatedly due to the loop's closure capturing the final value of i
.
JavaScript
for (i = 1; i <= 5; i++){
setTimeout(() => {
console.log(i);
},i*1000)
}
console.log('Printed Immediately');
Output:
Printed Immediately
6
6
6
6
6
Explanation: The code logs 'Printed immediately', then '6' five times. setTimeout
stores each iteration's reference, and executes after the loop ends when i
is 6, showing '6' repeatedly.
Uses of setTimeout function
- Delay Execution:
setTimeout()
allows you to delay the execution of a function or code block by a specified amount of time, which is useful for scheduling tasks. - Asynchronous Operations: It helps in managing asynchronous operations by deferring actions until other code has executed, keeping the event loop non-blocking.
- Task Scheduling: It is used to schedule tasks that need to be executed after a certain interval, improving the timing control within applications.
- Simulation of Delays: It can simulate network delays or processing times during testing and development, helping to create realistic scenarios for debugging and performance testing.
Similar Reads
D3.js timeout() Function The d3.timeout() function in D3.js is used to automatically stop the function or the timer after a particular interval of time. It works same as setTimeOut() function in JavaScript. Syntax: d3.timeout(callback, delay); Parameters: This function accepts two parameters as mentioned above and described
2 min read
How to understand various snippets of setTimeout() function in JavaScript ? When dealing with JavaScript, there will be times when you wish to run a function after a particular period of time. For this, we use setTimeout(), an asynchronous method that sets a timer, which then executes the function or specified piece of code once the timer expires. In this article, we will b
3 min read
What is the use of setInterval() method in Node.js ? The setInterval() method helps us to repeatedly execute a function after a fixed delay. It returns a unique interval ID which can later be used by the clearInterval() method which stops further repeated execution of the function. Syntax: const intervalId = setInterval(func, [delay, arg1, agr2, ...,
3 min read
Node.js Timeout Timer Class The timer module is used for scheduling functions which will be called at some future period of time. It is a global API So, there is no need to import (require("timers")) to use it. Timeout Class has an object (setTimeout()/setInterval()) which is created internally to scheduled actions, and (clear
3 min read
Underscore.js _.throttle() Function The _.throttle() method in underscore is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds. The throttled function has a cancel method which is used to cancel func calls that are delayed and it also has a flush method which is used t
2 min read
How to End setTimeout After User Input ? To end setTimeout after user input, you can use the clearTimeout function. The clearTimeout() function in JavaScript clears the timeout which has been set by the setTimeout() function before that. Syntax:clearTimeout(name_of_setTimeout);ApproachSet an initial countdown time (e.g., 5 seconds) and a v
3 min read
Tensorflow.js tf.time() Function Tensorflow.js is an open-source library that was developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment. The tf.time() function is used to execute the stated function, f() as well as return a promise in order that determine
2 min read
Using setTimeouts in React Components The setTimeout method in React enables the execution of a function after a specified time interval. This functionality is pivotal in web development for implementing time-based behaviors, offering a spectrum of applications ranging from user interface enhancements to asynchronous operations. The set
6 min read
Why to Use Node.js For Backend Development? JavaScript is the universal language for building web applications. It is used in frontend (client-side) and backend (server-side) development as well. But the truth that the beauty of the front-end relies on the back-end can't be denied. This is when NodeJS comes into the picture. Node.js is the be
7 min read
What is a callback function in Node? In the context of NodeJS, a callback function is a function that is passed as an argument to another function and is executed after the completion of a specific task or operation. Callbacks are fundamental to the asynchronous nature of NodeJS, allowing for non-blocking operations and enabling effici
2 min read