setTimeout和每个数组 [英] setTimeout and array each
本文介绍了setTimeout和每个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对使用setTimeout和每个迭代器感到困惑。如何重写以下内容,以便控制台在5秒钟的延迟后输出每个名称?目前,下面的代码会在5秒钟后立即打印所有名称。我想:
I'm confused with using setTimeout and the each iterator. How can I rewrite the following so that the console outputs each name after a delay of 5 seconds? Currently the code below prints all the names at once after 5 seconds. I would like to:
1)等待5秒钟,然后打印kevin
2)等待5秒钟,然后打印mike
3)等待5秒钟,然后打印sally
1) wait 5 seconds, then print kevin
2) wait 5 seconds, then print mike
3) wait 5 seconds, then print sally
var ary = ['kevin', 'mike', 'sally'];
_(ary).each(function(person){
setTimeout(function(){
console.log(person);
}, 5000);
});
推荐答案
您可以创建一个名为 offset
,使计时器为数组中的每个人多等待5秒,例如:
You could create a variable called offset
that makes the timer wait 5 seconds more for each person in the array, like so:
var ary = ['kevin', 'mike', 'sally'];
var offset = 0;
_(ary).each(function(person){
setTimeout(function(){
console.log(person);
}, 5000 + offset);
offset += 5000;
});
这篇关于setTimeout和每个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文