是否有可能捕获setTimeout
中每秒钟的tick ?假设在一个场景中,我需要在5秒后注销用户,并显示一条消息,比如在div
中,说"您将在5秒内注销"。然后是4、3、2、1,在timeOut
,
setTimeout(function(){
$("#myDiv").text("you will be logged out in " + n + " seconds");
//"n" being tick of each second.
},5000)
我在互联网上搜索了这个,但我找不到解决方案。或者在这种情况下可以用setInterval
做的任何事情在这里也是很好的点。对此有什么想法或启示吗?
您可以将setInterval
方法与clearInterval
方法结合使用:
var n = 5;
var timeoutID = window.setInterval(function() {
// this callback will execute every second until we call
// the clearInterval method
$('#myDiv').text('you will be logged out in ' + n + ' seconds');
n--;
if (n === 0) {
// TODO: go ahead and really log the dude out
window.clearInterval(timeoutID);
}
}, 1000);
您可以使用一个全局变量来显示tick。像下面的
var counter = 5;
var timeInterval= setTimeout(function(){
$("#myDiv").text("you will be logged out in " + n + " seconds");
//"n" being tick of each second.
counter = counter - 1;
clearInterval(timeInterval) if(counter==0)
},1000)