한 페이지에 간단한 카운트 다운을 거의 (5 ~ 25 개) 배치하려고하는데 브라우저 충돌 (100 % CPU로드)
누군가 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);
}
코드의 문제는 함수 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);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다