koninos
koninos

Reputation: 5357

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'

Upvotes: 1

Views: 48

Answers (2)

m.spyratos
m.spyratos

Reputation: 4229

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.

Upvotes: 0

Quentin
Quentin

Reputation: 944083

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

Upvotes: 3

Related Questions