setInterval countDown更新时间
问题描述:
我有这countDown,每次我按下按钮我想添加5多秒。setInterval countDown更新时间
当更新时间时,函数也会计算新值,但也是旧值。
有人可以解释我为什么吗?
http://jsfiddle.net/xqdj3uz8/1/
$('button').on('click', function() {
var newtime = parseInt(seconds + 5);
timer(newtime);
});
答
您可以通过使用全局变量来跟踪的左秒为单位尝试。点击按钮将增加这个变量。
var timeLeft = 10;
function timer() {
var i = setInterval(function() {
$('span').text(timeLeft);
timeLeft--
if (timeLeft === 0) clearInterval(i)
}, 1000)
}
function addSeconds(n) {
timeLeft += n
}
timer()
$('button').on('click', function() {
addSeconds(5)
});
答
请使用
function timer(time) {
var interval = setInterval(countDown, 1000);
function countDown() {
time--;
$('span').text(time);
if(time === 0) {
clearInterval(interval);
}
}
$('button').on('click', function() {
time=parseInt(time + 5);
$('span').text(time);
});
}
var seconds = 5;
timer(seconds);
答
尝试这个
var gblTime=0;
function timer(time) {
var interval = setInterval(countDown, 1000);
gblTime = time;
function countDown() {
gblTime--;
$('span').text(gblTime);
if(gblTime <= 0) {
clearInterval(interval);
}
}
}
var seconds = 5;
timer(seconds);
$('button').on('click', function() {
gblTime = parseInt(gblTime +1+ 5);
//timer(newtime);
});
+0
@Marius - 请参阅上面的JSFIDDLE链接 - 它正在工作 – prog1011 2015-02-24 09:36:15
答
您要添加新的区间是独立形式对方,尝试:
var time = 5;
var seconds = 5;
function timer() {
var interval = setInterval(countDown, 1000);
function countDown() {
$('span').text(time);
if(time === 0) {
clearInterval(interval);
}
time--;
}
}
timer();
$('button').on('click', function() {
if(time==0){
timer();
}
time += seconds;
});
http://jsfiddle.net/xqdj3uz8/3/ – kuba 2015-02-24 09:23:19