javascript - Execute a .map() function every 'x' amount of seconds -


i have function:

function getpattern (sequence) {   sequence.map(pod => pod.classlist.add('playing'))   // rest of code } 

how execute pod.classlist.add('playing') every, let's say, 2 seconds? moreover, want keep synchronous ensure //rest of code run after pod iterations have finished.

(for wondering, sequence array of html nodes)

edit have tried:

sequence.foreach(pod => settimeout(() => { pod.classlist.add('playing') }, 2000)) sequence.map(pod => settimeout(() => { pod.classlist.add('playing') }, 2000))  settimeout(() => {  sequence.map(pod => pod.classlist.add('playing')) }, 2000) setinterval(() => {  sequence.map(pod => pod.classlist.add('playing')) }, 2000) 

however suffering both problems wanted avoid in question: addclass isn't delayed; iterations execute 'at same time'. moreover, // rest of code being run asynchronously (a.k.a noticing console.log's immediately).

you can use promises spread out adding class each node , run code after nodes have been processed.

var myarrayofdomnodes = array.from(document.queryselectorall('p'));    addclassessequentially(myarrayofdomnodes).then(_ => {      // code run after classes have been added.      console.log('all done');  });    function addclassaftertwoseconds(el) {      return new promise(res => {          settimeout(_ => {              el.classlist.add('playing');              res();          }, 2000);      });  }    function addclassessequentially(sequence) {      let item = sequence.shift();      return item ? addclassaftertwoseconds(item).then(addclassessequentially.bind(null, sequence)) : promise.resolve();  }
p.playing {    color : red;  }
<p>one</p>  <p>two</p>  <p>three</p>  <p>four</p>


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -