Javascript:在setInterval中强制进行新的循环迭代

编程入门 行业动态 更新时间:2024-10-27 04:29:39
本文介绍了Javascript:在setInterval中强制进行新的循环迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个setInterval循环.设置为3500毫秒,如下所示:-

I have a setInterval loop. It's set to 3500 milliseconds, like so:-

var loop = setInterval(function() { /*stuff*/ }, 3500);

如果发生某种情况,在填充"的某一点上,我想强制循环的新迭代,并且在3500毫秒内不等待.那怎么可能?是继续吗,还是我只需要以不同的方式制定流程?

At one point in 'stuff' if a certain situation occurs, I want to force a new iteration of the loop and NOT WAIT for the 3500 milliseconds. How is that possible? Is it continue or do I just need to frame the process differently?

推荐答案

您可以尝试使用setTimeout而不是setInterval编写匿名自调用函数:

You could try writing an anonymous self-calling function using setTimeout instead of setInterval:

var i = 0; (function() { // stuff i++; if (i % 2 == 0) { // If some condition occurs inside the function, then call itself once again // immediately arguments.callee(); } else { // otherwise call itself in 3 and a half seconds window.setTimeout(arguments.callee, 3500); } })();​ // <-- call-itself immediately to start the iteration

更新:

UPDATE:

由于在注释部分表达了对arguments.callee用法的分歧,因此,使用命名函数可以实现相同的目的:

Due to a disagreement expressed in the comments section against the usage of arguments.callee, here's how the same could be achieved using a named function:

var i = 0; var doStuff = function() { // stuff i++; if (i % 2 == 0) { // If some condition occurs inside the function, then call itself once again // immediately doStuff(); } else { // otherwise call itself in 3 and a half seconds window.setTimeout(doStuff, 3500); } }; doStuff();

更多推荐

Javascript:在setInterval中强制进行新的循环迭代

本文发布于:2023-10-29 07:42:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539113.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:迭代   Javascript   setInterval

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!