如何在java脚本中停止间隔15秒?

时间:2015-10-07 19:58:06

标签: javascript

我想在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消息。 我该怎么做? 这是我的小提琴: http://jsfiddle.net/eo39peh6/

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);