Temporarily disable the JS event and find out how JS event handling works.

I suggested that I can simply set the onhashchange event handler to null, change the hash, and then set the onhashchange event handler, but consider the following code:

window.onhashchange = null; window.location.hash = "this_should_not_concern_you"; window.onhashchange = function() {alert('chunky bacon')}; doOtherStuff(); 

So, when has has is changed, the event handler for the hash does not change, but I still get warnings for the "short bacon".


Update I decided to go with the setInterval solution from Jed. And although it works (thanks to Jed), it is ugly and fragile. If there was a (somewhat paradoxical) onAllEventsHandled event, then I could place my onhashchange subscription and be sure that I do not accidentally warn the "short bacon" just because doOtherStuff() takes 2 seconds.

+4
source share
3 answers

It works asynchronously. Try the following:

 window.onhashchange = null; window.location.hash = "this_should_not_concern_you"; setTimeout( function() { window.onhashchange = function() {alert('chunky bacon')};}, 500 ); 

A delay of 500 ms gives enough time to set the handler after changing the hash. (Even for 0ms, it will probably be enough to get things done.)

+2
source

You are code that is part of one event loop, and because of this, when the event starts the next loop, your handler is in its place. A simplified example of an event loop would be:

  • Event management
  • Delete call stack
  • Waiting for events (return to step 1)

When the hash changes in the same event loop as you assign the callback to, it is not processed until the next event loop that already has it sits there, waiting for the event.

 window.location.hash = 'test1'; window.onhashchange = function() { console.log(window.location.hash); }; window.location.hash = 'test2'; 

This code will write #test2 twice. The handler fires twice, but the value after the handler starts is test2, both times.

+2
source
 window.onhashchange = null; window.location.hash = "this_should_not_concern_you"; window.onhashchange = function() { window.onhashchange = function() {alert('chunky bacon')}; }; window.location.hash = "this_should"; 
0
source

All Articles