Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling setTimeout in a loop not working as expected

The following JavaScript ought to (in my mind) play a sequence of notes 0.5 sec apart. But it plays them all as a single simultaneous chord. Any idea how to fix it?

function playRecording() {
    if (notes.length > 0) {
        for (var i = 0; i < notes.length; i++) {
            var timeToStartNote = 500 * i;
            setTimeout(playNote(i), timeToStartNote);
        }
    }
}

function playNote(i) {
    var noteNumber = notes[i];
    var note = new Audio("/notes/note_" + noteNumber + ".mp3");
    note.play();
}
like image 302
user2942693 Avatar asked Oct 31 '13 18:10

user2942693


1 Answers

JavaScript closures, wrap this in a self-executing function:

for (var i = 0; i < notes.length; i++) { 
    (function(i) {
       var timeToStartNote = 500 * i;
       setTimeout(function() {
           playNote(i)
       }, timeToStartNote);
    })(i)
}
like image 200
tymeJV Avatar answered Oct 13 '22 00:10

tymeJV