ziiweb ziiweb - 2 years ago 71
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download