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

Multiple countdowns on one page (js / jQuery)

本文关键字:倒计时 jQuery js 一个      更新时间:2023-09-26

我试图在一个页面上放置几个(从 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);
}

代码的问题在于函数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);
}