DEV Community

Cover image for ⏰ Trust issues with setTimeout()🤯 **Learn with examples**
Fidal Mathew
Fidal Mathew

Posted on

⏰ Trust issues with setTimeout()🤯 **Learn with examples**

Hi everyone! Happy holidays, I hope you’re doing well. And yes, you read the title right. If you put a set setTimeout() of 5 seconds, it doesn’t mean you’ll see the output in 5 seconds. Don’t believe me? Let’s learn about setTimeout in detail.

How does JavaScript work?

Javascript operates using a call stack and execution context to manage and execute code.

Call stack:

  • The call stack is a data structure that records where in the program we are. It keeps track of the functions that are being called from the main execution context down to nested functions.
  • Whenever a function is invoked, a new frame is pushed onto the call stack to keep track of its execution context (local variables, parameters, etc.).
  • When a function finishes executing, its frame is popped off the stack, and the control returns to the context that called it.

Execution Context:

  • Execution context is a wrapper that contains information about the environment in which the current code is being executed.
  • Global Context: This is the default context where the code runs if it's not inside any function.
  • Function context: It is formed when a function is called, it contains local variables, parameters, references to its outer environment (for closures), and the 'this' keyword's value.

callstack and execution context

How does setTimeout work?

setTimeout is not treated as a normal function. They don’t create a function context and get added to the call stack. So, how do they operate?

When setTimeout is called, it becomes a part of the browsers' Web APIs to be executed after the specified time delay. And when it is completed, it doesn’t add itself to the call stack, rather it gets added to the callback queue.

Callback queue:

Also, known as task queue, is where asynchronous tasks, like the ones scheduled by setTimeout(), fetch(), are placed after their execution has finished. And once, the call stack becomes empty, these tasks are pushed into the task for execution.

NOTE: The callback queue waits for all the synchronous tasks to be executed and only then pushes its content.

Examples

Let’s take a look at some interesting examples for setTimeout(). Try guessing the output and maybe you can try it out on your system.

Example 1:

Here’s a code snippet containing setTimeout(0).



console.log("Start");

setTimeout(function timeOut() {
    console.log("timeout");
}, 0);


Enter fullscreen mode Exit fullscreen mode

console.log("End");

From a person, who doesn’t know how JavaScript gets executed, they would probably say the output to be:

wrong output

But, here’s the correct one:

correct output

The reason is simple, when the setTimeout(0) is called, even for 0 secs, it goes to the web APIs to get its tasks completed and then stays in the callback queue until all synchronous tasks are completed such as console.log(). So, after it is completed, we see the output of console.log(“Timeout”).

Example 2:

Here’s a code snippet containing setTimeout(5000) and the code below takes about 10 seconds to execute. Suppose, it is a massive codebase and takes just a lot of time to execute. We won’t be writing it down, but fulfilling the need via a while loop to check the time after 10 seconds.



console.log("Start");

setTimeout(function timeOut() {
    console.log("Timeout -- 5 seconds");
}, 5000);


let startDate = new Date().getTime(); //time in seconds
let endDate=  startDate;

while(endDate < startDate+10000){ // 10 seconds

    endDate =  new Date().getTime();

}
console.log("End -- 10 seconds");


Enter fullscreen mode Exit fullscreen mode

The expected output would be:

expected output

But, the actual output is:

actual output

So, why does this happen? 🤔
Usually, the lines of code we write get executed in a fraction of a second, and then the setTimeout() function gets loaded in the execution context. But, in this case, the synchronous functions take 10 seconds to execute. The “End” word gets logged out after 10 seconds and we get output “Timeout” after that.

So, I hope you learned about the unique nature of setTimeout() in this article. A simple thing to remember is it always gets executed after all the synchronous tasks. Feel free to share any interesting facts about JavaScript!

Till then, follow me for more Javascript and web-related articles! 😁

Connect with me on-

Top comments (2)

Collapse
 
rushi_sutar profile image
Rushikesh

Nice explanation..

Collapse
 
fidalmathew profile image
Fidal Mathew

Thanks a lot! 😄