Javascript 延迟3秒的阵列显示索引

Javascript 延迟3秒的阵列显示索引,javascript,Javascript,在下面的代码中,我试图保持超时,但它不起作用。我正在发送数组,希望数组索引延迟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,2

在下面的代码中,我试图保持超时,但它不起作用。我正在发送数组,希望数组索引延迟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])

SetTimeout
应该是
SetTimeout
。它是区分大小写的

您同时设置了4个超时。因为每个循环都要增加
i
的值,所以循环结束时它将是
4

我不确定你想做什么,但也许你想要这个

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

使用以下命令:

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]);
函数displayIndex(arr){//数组作为输入
var i=0;
无功电流;
run=setInterval(function(){//在变量中设置函数,以便稍后停止
如果(i=arr.lentgh
}
},3000);    
}
显示索引([10,20,30,40]);
1st:如果在
for
中使用
setTimeout
setInterval
函数,这是一个问题,因为所有这些都是循环方式(前两个是带时间间隔的循环)。aa和
setTimeout
只需在内部运行一次代码

注意:
setInterval
需要一个函数来停止它
clearInterval
,所以我在里面放了一个
if

2nd:您没有将
currentI
i
设置为
arr
运算符的向量。例如,当您运行数组时,格式为:
arr[currentI]


怀疑?

其行为异常的原因:

案例1:在第一个代码段中,
setTimeout()
正在将函数添加到事件队列中,以便在主线程没有更多代码可执行后执行。
i
变量作为引用传递,因此上次修改的值将在每次调用中打印,因为它是通过引用传递的

案例2:在本例中,由于要传递4个显式引用,因此值不同,但执行顺序相同(即同步和瞬时)

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

解决方法:如果您不想在代码中实现阻塞行为,我建议对浏览器使用类似的
process.hrtime()
(在
窗口
对象上应该有一个计时方法,并编写一个
while
循环,该循环显式循环直到一秒钟过去


建议:我有点困惑,为什么你需要这样的代码阻塞?

setTimeout
而不是
setTimeout
JavaScript是一种区分大小写的语言。推理是有帮助的,我不需要任何特定于阻塞代码的东西,但我只是在使用JavaScript尝试这个算法,直到@gaba才明白我是索尔。我想你的建议也包括一些小问题。我会核实的。泰。
setTimeout(function () {
  var currentI = i; //Store the current value of `i` in this closure
  console.log(currentI);
}, 3000);
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]);