Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptWhat is the purpose of setTimeout() function in JavaScript ?

What is the purpose of setTimeout() function in JavaScript ?

The setTimeout() is a method inside the window object, it calls the specified function or evaluates a JavaScript expression provided as a string after a given time period only once. The following output shows the existence of setTimeout() method inside the window object.

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 kinds of executions. It is also used for animations and DOM manipulations in jquery.

Syntax: 

setTimeout(function, time);

Parameters: 

  • 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 the setTimeout() method.

In Javascript, everything is executed inside the execution context. So a global execution context will be created and pushed into the call stack of the JavaScript engine. Inside the Global execution context, the memory allocation phase starts and all the variables and functions get space in Memory Heap. The function named alertAfter3Seconds will get space in Heap and there are no variables.

The thread of execution starts and the JavaScript engine encounters the console log statement, consequently, a line will be printed on the console of the chrome developers tool. The setTimeout() function registers the function provided as a parameter to be executed after some provided(3000) milliseconds. The browser keeps a record of it internally and as soon as the timer expires, it enqueues that function to the callback queue. Now as soon as the call stack becomes empty, the event loop which was running constantly will notice it and dequeue that callback function from the callback queue and push it into the call stack. In this case, there is only one execution context which is global, and as soon as the console.log statement executes there is nothing in the call stack so the event loop will dequeue the callback function from the callback queue and push it into the call stack.

When our callback function is inside the call stack it is quite obvious to understand what is going to happen. Inside the function, there is a simple alert.

 

Javascript




<script>
    console.log("This is the demo of setTimeout");
      
    function alertAfter3Seconds() {
        alert("3 Second completed hi!");
    }
    setTimeout(alertAfter3Seconds, 3000);
</script>


Output: This is the alert showing after 3 seconds due to the 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 how much time it has to wait for 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 is inside setTimeout() and these two variables will get memory in the 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 the callback queue.

Concurrently JavaScript engine is busy executing its code. We have stored the current date in a variable. The Date.now() returns the milliseconds elapsed since the epoch time. So to convert it into seconds we have divided it by 1000. In the next one, we have assigned the current time + 5 for a purpose.

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 the 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 the callback queue, the function will be in the js call stack only when the call stack becomes empty. 

Javascript




<script>
    console.log("Hi, I am the first Line of Code");
      
    setTimeout(() => {
            console.log("Hi, I am the console.log inside setTimeout")
        },
        1000
    );
      
    let currentTime = Date.now() / 1000;
    let expectedTime = currentTime + 5;
      
    console.log("Executing 5 Seconds inside Loop");
    console.log("Timer Starts & Current Time " + currentTime);
      
    while (currentTime < expectedTime) {
        currentTime = Date.now() / 1000;
    }
      
    console.log("Timer Ends & Current Time " + currentTime);
    console.log("Hi, I am the Last Line of Code");
</script>


Output:

RELATED ARTICLES

Most Popular

Recent Comments