一页上有多个倒计时(js / jQuery)

时间:2016-02-10 04:17:52

标签: javascript jquery

我试图在一个页面上放置少量(从5到25个)简单倒计时并且浏览器崩溃(100%CPU负载)

请帮助别人!

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);
}

1 个答案:

答案 0 :(得分:1)

代码的问题在于无限地立即调用函数timersInit()

请注意,函数在setTimeout内立即调用,返回值用作超时后调用的函数。这导致函数无限地递归调用,直到浏览器被挂起。

function timersInit() {

    ....

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

要解决此问题,您可以使用函数引用而不是调用它。

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

为了提高性能,我建议缓存元素并仅循环显示可见元素。

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);
}