开发者

Running setTimeout indefinitely in JavaScript as an event handler

开发者 https://www.devze.com 2023-03-05 10:54 出处:网络
I building a page that will depend entirely on JavaScript. Whenever a user clicks a link or button, it changes the hash value of the URL (#doSomething).

I building a page that will depend entirely on JavaScript. Whenever a user clicks a link or button, it changes the hash value of the URL (#doSomething).

I have setup a function the check the hash value every 200ms for changes, in other words a custom event handler, and run some code depending on what the value is. Right now it seems to be fine since I am still in the development process and my page is pretty light.

Here is my question is it ok to have a script run indefinitely checking this value? or is going to affect performance when the page has more content and 开发者_C百科stuff to work with?

Is there a better way to setup a script to detect the changes of the URL hash?

Here is my script:

var currenthash = (window.location.hash)?window.location.hash: '';
addEvent(window,'load',function () {
    if (currenthash != ''){
        hashChanged();
    }
    var timeInterval = setInterval(function () {
        if (window.location.hash != currenthash) {
            hashChanged();
            currenthash = window.location.hash;
        }
    },1000);
});

var hashChanged = function (str) {
    var id = window.location.hash.replace("#",'');
    var selected = $id(id);
    // do some more stuff

    }
}


It shouldn't be an issue if it is checking every 1000 milliseconds (I usually run mine at 100), but consider using the native event handler (hashchange) if it exists...

if ('onhashchange' in window) {
    addEvent(window, 'hashchange', hashChanged);
} else {
   // Poll like normal.
}

This will be save you having to poll in modern browsers supporting this event.


If the hash only changes on clicks, why not a click listener on the document, no need for setInterval or setTimeout at all and your function only runs when it needs to.


As long as the interval isn't too short, there is no problem with it.

0

精彩评论

暂无评论...
验证码 换一张
取 消