Javascript setTimeout in foreach: need help creating a closure

自作多情 提交于 2019-12-05 03:27:25
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[index]);
            playAllNotes(++index);
        }, 1000);
    }
}

There are two ways to do this:

1) Have a function that grabs one note every second until there are no more notes:

var interval = setInterval(function() {
  playNote(notes.shift()); // changes the notes array!
  if (!notes.length) clearInterval(interval);
}, 1000);

2) Start all the timers at the same time with different delays:

notes.forEach(function(note, index) {
  setTimeout(playNote.bind(null, note), index*1000);
});

You can use a counter, it's tricky but worth it if you are working with objects:

counter = 0;
$.each(object, function(index,item){
  counter++;
  var localCounter = counter;
  setTimeout(function{
   console.log('something')
  }, counter * 1000) // change one to number of milliseconds you need
})

First counter is global, so if we don't user var localCounter we would execute all timeouts at the same time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!