Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.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
for循环之间的Javascript超时?_Javascript_Jquery - Fatal编程技术网

for循环之间的Javascript超时?

for循环之间的Javascript超时?,javascript,jquery,Javascript,Jquery,因此,可能是对使用javascript提供的setTimeout方法的最佳方式有一些误解,但我在以合理的方式实现它时遇到了困难 基本上,我有一个数组,其中的数字介于1-4之间,每个数字对应一个松开的按钮 for(let i = 0;i < arr.length;i++){ view.renderPane(arr[i]) //All this does is set the .css 所以我尝试设置一个超时,以为我可以在超时时间内调用renderPane,但它所做的只是设置

因此,可能是对使用javascript提供的
setTimeout
方法的最佳方式有一些误解,但我在以合理的方式实现它时遇到了困难

基本上,我有一个数组,其中的数字介于
1-4
之间,每个数字对应一个松开的按钮

for(let i = 0;i < arr.length;i++){
        view.renderPane(arr[i]) //All this does is set the .css

所以我尝试设置一个超时,以为我可以在超时时间内调用renderPane,但它所做的只是设置了一系列超时,基本上在X秒(或毫秒)后触发。有没有办法在for循环中每隔1秒调用
renderPane(窗格)
函数(设置延迟)?或者我需要设置其他内容吗?

无需使用循环,只需创建一个函数,该函数使用
setTimeout
连续调度自身,直到完成为止-在这种情况下,它在每次调用中从数组中移除一个项,并在数组为空时停止:

(function callee() {
    view.renderPane(arr.shift());
    if (arr.length)
        setTimeout(callee, 1000);
})();
例如:


有许多其他方法可以实现此行为,但这应该为您提供一个良好的起点。

您需要每1秒调用一次函数:您尝试过吗interval@NairAthul间隔是否会阻止for循环运行?由于我只需要多次调用
renderPane
函数(基于数组长度),因此每隔1秒就会触发一次yes interval(如您提供的)。您还可以在需要时清除/停止计时器,或者尝试一个接一个地渲染窗格,每个窗格之间有一个延迟?完成所有操作后,是否希望它“环绕”到第一个窗格(并无限期地继续)?不,基本上它需要渲染然后清除(例如渲染并点亮按钮后的第二个)。想象一下西蒙的游戏。灯光闪烁黄/红/黄/蓝…等。。然后停止(表示计算机移动的数组长度)
(function callee() {
    view.renderPane(arr.shift());
    if (arr.length)
        setTimeout(callee, 1000);
})();