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