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.
source share