简体   繁体   中英

Asynchronous code execution

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'

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM