how to set a timeout on an array element

Solutions on MaxInterview for how to set a timeout on an array element by the best coders in the world

showing results for - "how to set a timeout on an array element"
Noémie
08 May 2019
1var ary = ['kevin', 'mike', 'sally'];
2
3for(let i = 1; i <= ary.length; i++){
4    setTimeout(function(){
5        console.log(ary[i - 1]);
6      }, 5000 * i); 
7}
8
Eduardo
24 Jul 2019
1   
2function ArrayPlusDelay(array, delegate, delay) {
3  var i = 0
4  
5  function loop() {
6  	  // each loop, call passed in function
7      delegate(array[i]);
8      
9      // increment, and if we're still here, call again
10      if (i++ < array.length - 1)
11          setTimeout(loop, delay); //recursive
12  }
13
14  // seed first call
15  setTimeout(loop, delay);
16}
17
18// call like this
19ArrayPlusDelay(['d','e','f'], function(obj) {console.log(obj)},1000)
Miguel
19 Aug 2017
1function ArrayPlusDelay(array, delegate, delay) {
2  var i = 0
3  
4   // seed first call and store interval (to clear later)
5  var interval = setInterval(function() {
6    	// each loop, call passed in function
7      delegate(array[i]);
8      
9        // increment, and if we're past array, clear interval
10      if (i++ >= array.length - 1)
11          clearInterval(interval);
12  }, delay)
13  
14}
15
16ArrayPlusDelay(['x','y','z'], function(obj) {console.log(obj)},1000)