[英]stop javascript countdown timer with onclick event
我需要幫助,我為帶有進度條的倒數計時器制作了一個javascript函數,這是代碼
function progress(timeleft, timetotal, $element) {
var progressBarWidth = timeleft * $element.width() / timetotal;
$element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, 'linear').html('');
$('#time_wrap').html('<span id="timer">'+timeleft+'</span>');
if(timeleft > 0) {
setTimeout(function() {
progress(timeleft - 1, timetotal, $element);
}, 1000);
}else{
setTimeout(function() {
submitdata();
}, 1000);
}
};
我需要使用onclick事件停止計時器,例如: <input type="button" onclick="stoptimer();">
如何使用stoptimer()函數停止計時器?
您正在尋找的是clearTimeout 。
您可以將代碼修改為:
var timer = null;
function progress(timeleft, timetotal, $element) {
var progressBarWidth = timeleft * $element.width() / timetotal;
$element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, 'linear').html('');
$('#time_wrap').html('<span id="timer">'+timeleft+'</span>');
if(timeleft > 0) {
timer = setTimeout(function() {
progress(timeleft - 1, timetotal, $element);
}, 1000);
} else{
timer = setTimeout(function() {
submitdata();
}, 1000);
}
// You can use this to bind event only after the timer is set.
// $('#stop-btn').on('click', function() {
// clearTimeout(timer);
// });
};
function stoptimer() {
clearTimeout(timer);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.