Trust Issues With setTimeout()
Hi There! All of us have some trust issues in our lives at one point of time, but here also we have yet another trust issue with setTimeout(). Wondering what is it? Let’s me give you the details!..
setTimeout() method set for delay of 5 seconds not always wait for 5 seconds, it could be more 6, 7 or 10!! How so? Let’s understand through an example.
The example you are seeing above for example if after the setTimeout method there are millions of lines of code which takes for example 10 seconds to execute therefore the call stack won’t be free for 10 seconds and post that it will be available to move the callback function from callback queue to call stack and execute it. Therefore, instead of taking 5 seconds the setTimeout method took 10 seconds to execute thereby not working as we were expecting it to.
Get Neha Prabhakar’s stories in your inbox
Join Medium for free to get updates from this writer.
Now how could we create such a scenario to block the main thread for 10 seconds. There is a sample program you can run to execute and know how it is done below.
Output:
Start
End
While Expires // After 10 seconds
callback
Note: There is only 1 call stack because JavaScript is a single-threaded language.
What if we set timer of 0 seconds?What will happen? Will it execute first? Let’s see:
The output will be:
Start
End
Callback
Yes, the output will be the same and will go through the same process. The above can be used if we want to defer some piece of code.
Hope this was helpful and easy to understand. If you found this blog helpful please go through my profile and have a look at some other interesting content. See you in next one! :) Until then..





