We all have used alarms or reminders several times, this setTimeout() method also has the same purpose in web applications. We use this to delay some kind of executions. It is also used for animations and DOM manipulations in jquery.
- function: It is the reference to a function that is going to run after a given time.
- time: The milliseconds after which the given function will execute.
Return value: It returns a timer Id which can be useful later in case when you want to clear that countdown timer for function.
Example 1:The following demonstrates the basic demo of setTimeout() method.
When our callback function is inside the call stack it is quite obvious to understand that what is going to happen. Inside the function, there is a simple alert.
Output: This is the alert showing after 3 seconds due to setTimeout() method.
Note: The event loop will only push the callback function inside the call stack of the JS engine if it is empty. The function provided to setTimeout() does not need to be executed just after the given milliseconds, this is the minimum time after which the browser will enqueue that function into the callback queue, It is unpredictable for how much time it has to wait for being pushed into the JS engine call stack.
Example 2: The following demonstrates that the event loop will only push the function in the call stack when it is empty.
The global execution context will be created and pushed into the call stack of the js engine. Then the memory allocation phase starts and the function which is inside setTimeout() and these two variables will get memory in heap. During the thread execution phase, the first line of the console log gets printed. In the next line setTimeout() registers a function inside web APIs and then internally the timer starts, and as soon as the 1000 millisecond finishes, it gets enqueued in callback queue.
We are checking for a condition if the currentTime is less than expectedTime, expectedTime is holding the currentTime + 5. We are constantly changing the value of currentTime with the Date.now(). When the currentTime is no longer less than expectedTime, the loop breaks. The condition inside parenthesis will break the loop after 5 seconds. Our call stack is empty there is nothing to execute and the event loop which is waiting for this situation pushes the callback function inside the JS call stack. The function is in the call stack so it is simple to understand what is going to happen, simply a console.log statement which was inside the callback function executes. Did you notice the while loop took an extra 5 seconds to execute the code and then the callback function executed! As we have set the 1000 milliseconds to the set timeout, we were expecting to execute that callback function after 1 second. Actually, that provided milliseconds is the time after which the function will be in callback queue, the function will be in js call stack only when call stack becomes empty.