The setTimeout () function is used to add delay or scheduling the execution of a specific function after a certain period. It's a key feature of both browser environments and Node.js, enabling asynchronous behavior in code execution.
The setTimeout () method calls a function or evaluates an expression after a specified number of milliseconds. Tip: 1000 ms = 1 second. Tip: The function is only executed once. If you need to repeat execution, use the setInterval () method. Tip: Use the clearTimeout () method to prevent the function from running.
When setTimeout is called, it doesn’t execute immediately. Instead, it adds the callback to the message queue, which only runs when the call stack is clear. Example: console.log("Inside setTimeout"); Expected output: Even with a 0ms delay, the callback runs only after the synchronous code completes. 2.
There are two methods for it: setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval. These methods are not a part of JavaScript specification.
In this guide I’ll walk you through what setTimeout really does, why it matters, and how to use it without getting tripped up. Once it clicks, a lot of other confusing stuff in JavaScript suddenly makes more sense.