DEV Community

Cover image for Trust Issues with setTimeout()
Ankita
Ankita

Posted on

Trust Issues with setTimeout()

what is setTimeout()?
Special asynchronous functions like setTimeout, setInterval are provided to JS by the environment it is currently running on. For example in case of Chrome JavaScript runs on the V8 engine, and Fire Fox uses SpiderMonkey as its JavaScript engine etc.

The setTimeout() method calls a function after a number of milliseconds. It sets a timer which executes a function or specified piece of code once the timer expires.

Image description

setTimeout with delay of 5000 milliseconds does not always wait for exactly 5000 milliseconds. There are trust issues.

Image description

Let's take one example and make it clear:

Image description

JavaScript is single threaded. Every line of code goes into call stack and gets executed.

date.getTime() method return current time in milliseconds. so I note the time when the execution of the program starts. our JS makes a timer for callback function of setTimeout and execution goes to the next line.

Here we use for loop to make more time in execution of our synchronous code. so when the call stack is busy in the execution of for loop our sweet timer gets expires but our call stack is busy in for loop so does execute callback function. our callback function is waiting in queue.

When the call stack finishes its loop execution it immediately runs our callback function. In the callback function, we get that time in milliseconds and log the total time of execution which may be greater than our delay time.

How much time setTimout takes, it's all dependence on our execution stack.

Top comments (2)

Collapse
 
moopet profile image
Ben Sinclair

Just a heads up that the Markdown we use here supports syntax highlighting, and is generally more accessible than inserting an image of code. Images of text are an issue for people using screen readers, for example, and their content won't get picked up by the site's search facility.

You can add code blocks with 3 backticks: code block with colors example More details in our editor guide!

Collapse
 
ahana001 profile image
Ankita

Thanks For letting me know.