2015-10-07 56 views
1

我想打破一段时间的JS间隔,比如说15秒。 目前我的代码看起来是这样的:如何在java脚本中停止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语句的不仅仅是第二长 - 但后来我想继续显示其他信息。 我该怎么办? 这里是myfiddle: http://jsfiddle.net/eo39peh6/

+0

简单的答案,你不能。除了执行诸如警告/确认对话框外,您不能暂停JavaScript执行。你可以做的最好的是清除间隔并在15秒后重新启动它,但是你不能在回调中间暂停。 –

回答

1

您可以删除间隔,然后设置一个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);

0

您可以使用该功能clearInterval()

var myInterval; 
var delay = 15000; 
function check() { 
    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); 
    setTimeout(function() { 
     myInterval = setInterval(check, 1000); 
    }, delay); 

    } else { 
    //console.log(new Date()); 
    console.log("im in else"); 
    } 
} 

myInterval = setInterval(check, 1000); 
相关问题