Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  149] [ 7]  / answers: 1 / hits: 8184  / 11 Years ago, thu, february 20, 2014, 12:00:00

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?


More From » closures

 Answers
2

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[index]);
playAllNotes(++index);
}, 1000);
}
}

[#47562] Wednesday, February 19, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristani

Total Points: 318
Total Questions: 95
Total Answers: 106

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
;