简体   繁体   中英

Multiple countdowns on one page (js / jQuery)

I'm trying to place few (from 5 to 25) simple countdowns on one page and browser crashes (100% CPU load)

Help somebody pls!

function timersInit(){
    $('[data-countdown]').each(function() {
        var timerObject = $(this),
            time_left_nix = parseInt(timerObject.data('countdown')),
            time_left_h = Math.floor(time_left_nix / 3600),
            time_left_m = Math.floor((time_left_nix / 60) - (time_left_h * 60)),
            time_left_s = Math.floor(time_left_nix - (time_left_m * 60) - (time_left_h * 3600));

        timerObject.text(time_left_h + ":" + (time_left_m < 10 ? "0" + time_left_m : time_left_m) + ":" + time_left_s);
    });

    setTimeout(timersInit(), 1000);
}

The problem with your code is that the function timersInit() is being called immediately infinitely.

Notice that the function is called immediately inside setTimeout and the returned value is used as function to call after the timeout. This is causing the function to call recursively infinitely until the browser is hanged.

function timersInit() {

    ....

    setTimeout(timersInit(), 1000);
    // timersInit(): means call immediately
}

To solve the problem, you can use the function reference instead of calling it.

setTimeout(timersInit, 1000); // Removed `()` of `timersInit`

To improve the performance bit, I'll suggest to cache the elements and loop over only visible elements.

var countdownEl = $('[data-countdown]:visible'); // Cache

function timersInit() {
    countdownEl.text(function () { // Use cached version instead of diving into DOM
        var time_left_nix = parseInt($(this).data('countdown')),
            time_left_h = Math.floor(time_left_nix / 3600),
            time_left_m = Math.floor((time_left_nix / 60) - (time_left_h * 60)),
            time_left_s = Math.floor(time_left_nix - (time_left_m * 60) - (time_left_h * 3600));

        return time_left_h + ":" + (time_left_m < 10 ? "0" + time_left_m : time_left_m) + ":" + time_left_s;
    });

    setTimeout(timersInit, 1000);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM