Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to code after history.back()?

I have code like the following:

window.history.back();
myFunction(10);
  • Is history.back() a blocking / non-blocking call?

  • Is there an assurance that myFunction() will be executed? or will not be executed?

  • Is this a possible race condition where history.back() happens asynchronously and whether myFunction() is called depends on timing of uncontrollable events?

like image 530
teddbytee Avatar asked Aug 28 '14 07:08

teddbytee


Video Answer


1 Answers

The spec says that history.back queues a task.

The actual history manipulation code (which is internal to the JS implementation) will therefore be executed during the next run of the main event loop. Your call to myFunction executes synchronously in the current round of execution, so it will always be executed in compliant environments.

However, only synchronous code in myFunction is guaranteed to execute. Consider this example:

function myFunction() {
  console.log('synchronous');
  debugger

  setTimeout(function() {
    console.log('async');
    debugger
  })
}

window.history.back();
myFunction();

The first debugger statement is always hit. The second, which is deferred to a future event loop tick using setTimeout, will not.

This article is a good explanation of the JavaScript event loop

like image 190
joews Avatar answered Sep 20 '22 19:09

joews