1

I was playing around with this asynchronous code and while is expected that the callback will be executed after 1 ms after the setTimeout and the value of val will be the value that it has at that time, so I tried to increase the reassignments of val hoping to overcome the 1ms of delay, until the execution of callback, but no matter how many reassignments of val I add, the value of val is always the one of the last assignment. So the question is, does all these reassignments happen so quickly that 1ms is enough to execute them all before executing the callback or am I missing something here?

    function asyncFunction(callback) {
       setTimeout(callback, 1);
    }

    var val= '1';

    asyncFunction(function() {
       console.log('The value is ' + val);
    });
    val= '2';
    val= '3';
    //...
    //... more asignments

    val = '1000'

2 Answers 2

3

JavaScript will never interrupt a currently running function to do something else.

When you pass a function to setTimeout it will be called when all of the following conditions are true:

  • The time specified has passed
  • The minimum time for a setTimeout has passed
  • There are no other functions being executed

Further reading: Reasons for delays longer than specified

Sign up to request clarification or add additional context in comments.

Comments

0

Read MDN - Reasons for Delays longer than specified.


It's important to note that the function or code snippet cannot be executed until the thread that called setTimeout() has terminated. For example:

function foo() {
    console.log('foo has been called');
}
setTimeout(foo, 0);
console.log('After setTimeout');

Will write to the console:

After setTimeout
foo has been called

Because even though setTimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity, not immediately. Currently executing code must complete before functions on the queue are executed, the resulting execution order may not be as expected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.