Javascript setTimeout in foreach: need help creating a closure
I have this function notes.forEach(function(note) { setTimeout(function() { playNote(note); }, 1000); }); This doesn't work. It plays all the notes at the same time, instead of playing them sequentially with a 1 second gap in between. It looks like I need to have a closure here to make this work. Could someone help me fix this function so it would play the note with the delay between each note? Cracker0dks because all timeouts are set at the same time... Do something like this: playAllNotes(0); function playAllNotes(index) { if(notes.length > index) { setTimeout(function() { playNote(notes