我需要帮助,我为带有进度条的倒数计时器制作了一个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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句