[英]Multiple countdowns on one page (js / 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);
}
您的代碼的問題在於,立即無限次調用了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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.