![]() |
VOOZH | about |
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.
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.
window.setTimeout(function, 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.
Output:
Printed Immediately
Printed after 3 secondsExplanation: 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.
Output:
Printed Immediately
6
6
6
6
6Explanation: 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.
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.