ziiweb ziiweb - 7 months ago 19
Javascript Question

An array with integers (seconds) and setTimeout()

I have this code:

times.forEach(function(element) {
setTimeout(function() { alert(element); }, element * 1000);
});


and this array:
[1, 5, 1]


I expected an alert, first after 1 second, then another one after 5 seconds after the first, and the last one after 1 seconds after the second one, but the alert related to 1's are shown together at the beginning ...Any help?

Answer

You can use reduce to achieve what you want this way:

[1, 5, 1].reduce(function(p, c, i) {
   setTimeout(function() {
      console.log(new Date(), ['First', 'Second', 'Third'][i]);
   }, (p + c) * 1000);
   return p + c;
}, 0);