JavaScript Countdown Timer: Fixing setInterval Issues
There are a few issues with your code.
First, when you call 'setInterval', you need to pass a function reference as the first argument, not the result of a function call. In your code, you are immediately calling the 'countdown' function and passing its result to 'setInterval'. Instead, you should pass just the function name without the parentheses, like this:
timer = setInterval(countdown, 1000, 70);
Second, when you click on the '.clock' element, you are calling 'setInterval' again without clearing the previous interval. This means that multiple intervals will be running simultaneously, causing unexpected behavior. To fix this, you should clear the previous interval before starting a new one.
Here's the updated code:
var timer;
function countdown(time) {
if (time > 0) {
time--;
var minutes = Math.floor(time / 60);
var seconds = time % 60;
$('.clock').text(minutes + ':' + (seconds < 10 ? '0' : '') + seconds);
} else {
clearInterval(timer);
// trigger event here
}
}
timer = setInterval(countdown, 1000, 70);
$(document).on('click', '.clock', function() {
clearInterval(timer);
timer = setInterval(countdown, 1000, 20);
});
This code should fix the issues and make your timer work correctly.
原文地址: https://www.cveoy.top/t/topic/qytY 著作权归作者所有。请勿转载和采集!