简体   繁体   English

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

[英]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) 我试图在一页上放置一些(从5到25)简单的倒数,浏览器崩溃(100%CPU负载)

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. 您的代码的问题在于,立即无限次调用了timersInit()函数。

Notice that the function is called immediately inside setTimeout and the returned value is used as function to call after the timeout. 注意,该函数在setTimeout内部立即调用,并且返回的值用作超时后调用的函数。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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