2017-06-22 36 views
-2

在以下代码中的延迟的阵列的显示索引,我试图保持超时但它不工作。我发送数组并期待3秒延迟的数组索引。与3秒

function displayIndex(arr){ // array as input 
    for(var i=0;i<arr.length; i++){ 
     SetTimeout(function(){ 
      console.log(i); // always returns 4 
     },3000); 
    } 
} 

displayIndex([10,20,30,40]) 

更新:

var arr = [10,20,30,40]; 
function displayIndex(arr){ // array as input 
    for(var i=0;i<arr.length; i++){ 
    setTimeout(function() { 
     var currentI = i; //Store the current value of `i` in this closure 
     console.log(currentI); 
    }, 3000); 
    } 
} 

displayIndex(arr); // still prints all 4. 

此外,试图

arr.forEach(function(curVal, index){ 
    setTimeout(function(){ 
    console.log(index); 
    },3000); 
}); // prints 0 1 2 3 but I do not see 3 secs gap between each display, rather one 3 sec delay before everything got displayed. 
+1

'setTimeout',而不是'setTimeout' JavaScript是一种区分大小写的语言 – MrNew

回答

0

使用此:

function displayIndex(arr){ // array as input 
    var i=0; 
    var current; 
    run=setInterval(function(){ // set function inside a variable to stop it later 
     if (i<arr.length) { 
      current=arr[i]; // Asign i as vector of arr and put in a variable 'current' 
      console.log(current); 
      i=i+1; // i increasing 
     } else { 
      clearInterval(run); // This function stops the setInterval when i>=arr.lentgh 
     } 
    },3000);  
} 
displayIndex([10,20,30,40]); 

1:如果使用setTimeoutsetInterval功能for这是一个问题“职高里这一切都是循环的方式(前两个是与循环时间间隔)。 Aaand setTimeout只需运行一次代码。

注:setInterval需要一个函数来阻止它clearInterval,所以这就是为什么我把一个if内。

第二:您没有设置currentIiarr运营商的向量。当你运行一个数组的格式为:arr[currentI],例如。

疑问?

+1

它的工作原理毫无疑问,谢谢?!你。 – ram

0

SetTimeout应该setTimeout。这是区分大小写的。

你一次全部设置4个超时。既然你递增的i每个循环的价值,这将是4在循环的结束。

我真的不知道你想做什么,但也许你想要的吗?

setTimeout(function() { 
    var currentI = i; //Store the current value of `i` in this closure 
    console.log(currentI); 
}, 3000); 
0

之所以它的工作不正常:

案例1:在第一个片段,setTimeout()是增加的功能事件队列后,主线程没有更多的代码留给执行要执行。 i变量作为参考被传递,因此每次调用都会打印上次修改后的值,因为它是通过引用传递的。情况2:在这种情况下,由于您传递了4个显式引用,所以这些值是不同的,但执行顺序相同(即,同步和即时)。

原因:setTimeout()函数总是将传递给队列的函数作为最低保证,使其以延迟时间间隔运行。但是,如果函数之前的队列中存在代码,或者主线程中有任何其他代码,则延迟时间会更长。

解决方法:如果你不实现阻断代码的行为,我会建议使用的process.hrtime()为浏览器模拟(应该有window对象上的计时方法,写一个while循环,明确循环,直到第二经过

建议:我,为什么你需要在代码,阻止有些困惑

+0

推理是有帮助的,我不需要任何具体的阻止代码,但我只是尝试这个算法使用javascript,直到@gabad的sol才能算出来。我想你的建议也由nodejs组成。会检查。 TY。 – ram