我想将JS中的间隔打破一段时间,比如说15秒。 目前我的代码如下所示:
var currentDate = new Date().setMilliseconds(0)+4000;
check();
function check() {
//console.log("now "+new Date());
var dateOfText = new Date().setMilliseconds(0);
console.log("date1 "+currentDate);
console.log("date2 "+dateOfText);
if (currentDate - dateOfText ==0) {
console.log("hey I'm in if");
//how can I stay here for 15 seconds?
} else{
//console.log(new Date());
console.log("im in else");
}
}
var myInterval = setInterval(check, 1000);
并且我想在 if 语句中停留超过一秒的时间 - 但稍后我想继续显示 else 消息。 我该怎么做? 这是我的 fiddle : http://jsfiddle.net/eo39peh6/
最佳答案
您可以删除间隔,然后设置 15 秒的超时来重置间隔。
var myInterval;
function check() {
//console.log("now "+new Date());
var dateOfText = new Date().setMilliseconds(0);
console.log("date1 " + currentDate);
console.log("date2 " + dateOfText);
if (currentDate - dateOfText == 0) {
console.log("hey I'm in if");
clearInterval(myInterval); // stop interval
setTimeout(function() { // set timeout of 15 seconds
myInterval = setInterval(check, 1000); // reset interval
}, 15000);
} else {
//console.log(new Date());
console.log("im in else");
}
}
myInterval = setInterval(check, 1000);
关于javascript - 如何让javascript中的间隔停止15秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33001350/