Denea Novac Denea Novac - 1 year ago 74
CSS Question

Is setTimout(function, 100) going to affect performance?

I have a function that checks if the URL contains any of navigation hrefs every 100ms and if it does, the certain elements get class active added.


var checkActive = function(){
var path = window.location.pathname,
path = decodeURI(path),
path = path.replace(/[\/]/, "");

if ( window.location.pathname.indexOf(path) > -1 ) {
$('.navigation .nav li a[href*="' + path + '"]').parent().addClass('active');
$('.navigation .nav li a:not([href*="'+path+'"])').parent().removeClass('active');

(function loopingFunction() {
setTimeout(loopingFunction, 100);

Is this checking every 100ms going to affect the performance for other user with weaker PC's ?

P.s: I used this method since I'm using pushState, statechange and .load() to get my content updated, therefore the page itself doesn't refresh.

Answer Source

It's unlikely to cause any trouble. It's a small check done 10 times a second. But you can make it do less work by just using location.hash and comparing that (unparsed) value with the last one you used:

var lastHash = String(location);
var checkActive = function(){
    if (lastHash === String(location)) {
    // work...

However, you only need this on obsolete browsers. On any vaguely-modern browser, you can use the hashchange event instead, and you can easily detect whether it's supported:

if (typeof window.onhashchange !== "undefined") {
    // Vaguely modern, use the hashchange event
} else {
    // Obsolete, use a workaround

(Sorry, you're not just doing hash fragments.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download