Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在setInterval()中中断当前迭代并继续下一次迭代?_Javascript_Timing - Fatal编程技术网

Javascript 如何在setInterval()中中断当前迭代并继续下一次迭代?

Javascript 如何在setInterval()中中断当前迭代并继续下一次迭代?,javascript,timing,Javascript,Timing,就像continue用于中断当前迭代并继续下一个迭代一样,如何在JavaScript中的setInterval()中中断当前迭代并继续下一个迭代而不等待 var intervalID = window.setInterval( function() { if(conditionIsTrue) { // Break this iteration and proceed with the next // without waiting for 3 seconds.

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

var intervalID = window.setInterval( function() {
   if(conditionIsTrue) {
      // Break this iteration and proceed with the next
      // without waiting for 3 seconds.
   }
}, 3000 );
您可以“简单”(或不那么简单)清除间隔,然后重新创建它:

// 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 );

刚刚测试了它,它在循环中充当continue语句。对于现在发现这一点的其他编码人员,只需在setInterval内使用
return

var myRepeater = setInterval( function() {
   if(conditionIsTrue) {
      return;
   }
}, 1000 );
编辑:为了在中断循环的当前执行后立即执行,可以这样做(理论上,如果
conditionIsTrue
保持true,请注意递归问题):


迭代在哪里。有什么循环吗?你能告诉我们你想做什么吗。现在听起来你好像想炸毁你的网络浏览器。是的,我认为把
invervalFunction
分解成它自己的函数会让整个事情变得更有意义。这不会立即开始下一次迭代though@AniketSuryavanshi你说得对,我错过了。我为此添加了一个额外的解决方案。
function myFunction() {
    if(conditionIsTrue) {
       myFunction();
       return;
    }
    // Interval function code here...
}

var myRepeater = setInterval( myFunction, 1000 );