【问题标题】:How to break current iteration and continue with next iteration within setInterval()?如何中断当前迭代并在 setInterval() 中继续下一次迭代?
【发布时间】:2012-12-01 05:59:57
【问题描述】:

就像 continue 用于中断当前迭代并继续下一个迭代一样,我如何在 JavaScript 中打破 setInterval() 内的当前迭代并继续下一个间隔而不等待?

var intervalID = window.setInterval( function() {
   if(conditionIsTrue) {
      // Break this iteration and proceed with the next
      // without waiting for 3 seconds.
   }
}, 3000 );

【问题讨论】:

  • 你的迭代在哪里。有没有循环?
  • 您能否让我们更好地了解您想要做什么。目前听起来您正试图炸毁您的网络浏览器。

标签: javascript timing


【解决方案1】:

您可以“简单地”(或不那么简单地)清除间隔,然后重新创建它:

// run the interval function immediately, then start the interval
var restartInterval = function() {
    intervalFunction();
    intervalID = setInterval(intervalFunction, 3000 );
};

// the function to run each interval
var intervalFunction = function() {
    if(conditionIsTrue) {
      // Break this iteration and proceed with the next
      // without waiting for 3 seconds.

      clearInterval(intervalID);
      restartInterval();
   }
};

// kick-off
var intervalID = window.setInterval(intervalFunction, 3000 );

Here's a demo/test Fiddle.

【讨论】:

  • 是的,我认为将 invervalFunction 分解为自己的功能会让整个事情变得更有意义。
【解决方案2】:

刚刚对此进行了测试,它充当循环中的 continue 语句。对于现在发现此问题的其他编码人员,只需在 setInterval 中使用 return

var myRepeater = setInterval( function() {
   if(conditionIsTrue) {
      return;
   }
}, 1000 );

编辑:为了在中断当前循环执行后立即执行,可以改为执行类似的操作(理论上。如果conditionIsTrue 保持true,请注意递归问题) :

function myFunction() {
    if(conditionIsTrue) {
       myFunction();
       return;
    }
    // Interval function code here...
}

var myRepeater = setInterval( myFunction, 1000 );

【讨论】:

  • 这不会立即开始下一次迭代
  • @AniketSuryavanshi 你说得对,我错过了。我为此添加了一个额外的解决方案。
猜你喜欢
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
  • 2020-02-28
  • 2011-04-26
相关资源
最近更新 更多