在这个http://jsfiddle.net/kuox9ax2/中,我有一个倒计时的计时器。
我试图在return true
中作为startTimer()
,但后来我遇到JS是异步的,所以它立即返回true。
有人可以展示如何解决这两个问题吗?
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function() {
var time = 5, display = document.querySelector('#time');
var isDone = startTimer(time, display);
if (isDone) {
alert("a");
}
};
<div>Timeout in <span id="time">00:00</span> minutes</div>
答案 0 :(得分:3)
将您的间隔存储在变量中,并在达到0时调用clearInterval
.Javascript函数可以作为参数传递,通常称为回调。只需将函数作为参数传递,并在需要时调用它。
function startTimer(duration, display, callback) {
var timer = duration,
minutes, seconds;
var myInterval = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
// clear the interal
clearInterval(myInterval);
// use the callback
if(callback) {
callback();
}
}
}, 1000);
}
window.onload = function() {
var time = 5,
display = document.querySelector('#time');
startTimer(time, display, function() { alert('done'); });
};
&#13;
<div>Timeout in <span id="time">00:00</span> minutes</div>
&#13;
答案 1 :(得分:2)
您可以使用WindowTimers.clearInterval()
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var myInterval = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(myInterval);
doneFunction();
}
}, 1000);
}
window.onload = function() {
var time = 5, display = document.querySelector('#time');
startTimer(time, display);
};
function doneFunction(){
console.log("done !");
}
&#13;
<div>Timeout in <span id="time">00:00</span> minutes</div>
&#13;
答案 2 :(得分:1)
在异步操作完成后,您无法强制异步方法返回 - 这样做是一种反模式。
相反,您可以将函数传递给异步操作完成时要执行的方法。您还需要存储对setInterval()
的引用,并在计时器到达零时调用clearInterval()
。试试这个:
function startTimer(duration, display, callback) {
var timer = duration, minutes, seconds;
var interval = setInterval(function() {
var minutes = parseInt(timer / 60, 10)
var seconds = parseInt(timer % 60, 10);
display.textContent = ("00" + minutes).slice(-2) + ":" + ("00" + seconds).slice(-2);
if (minutes === 0 && seconds === 0) {
clearInterval(interval);
callback && callback();
}
timer--;
}, 1000);
}
window.onload = function() {
var time = 5, display = document.querySelector('#time');
startTimer(time, display, function() {
console.log("timer reached zero");
});
};
<div>Timeout in <span id="time">00:00</span> minutes</div>