Trigger function once on either hashchange or popstate

1000 Views Asked by At

I have this jquery code:

$(window).on('hashchange popstate', function() {
  someFunction();
});

I want to run someFunction() if the hash changes and also if the hash is removed. It seems like 'hashchange' does not fire if the hash is simply removed so therefore I have to use popstate as well. My problem now is that this is most often triggered twice, how can I avoid that?

I simply want the hashchange event plus the case when the hash is removed.

1

There are 1 best solutions below

0
On

You could try to debounce it a little bit:

$(window).on('hashchange popstate', function() {
    clearTimeout(this._debounced);
    this._debounced = setTimeout(someFunction/*,0*/);
});

To avoid global var:

$(window).on('hashchange popstate', function() {
    clearTimeout($(this).data('debounced'));
    $(this).data('debounced', setTimeout(someFunction/*,0*/ ));
});