Monday, June 3, 2024
168
rated 0 times [  175] [ 7]  / answers: 1 / hits: 26927  / 11 Years ago, sat, june 22, 2013, 12:00:00

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) 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);

});

More From » underscore.js

 Answers
14

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;
});

[#77483] Thursday, June 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarrodfletchers

Total Points: 75
Total Questions: 94
Total Answers: 95

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
jarrodfletchers questions
Sat, Sep 25, 21, 00:00, 3 Years ago
Mon, Jan 21, 19, 00:00, 5 Years ago
Sun, Dec 16, 18, 00:00, 6 Years ago
Sun, Nov 4, 18, 00:00, 6 Years ago
;