Display array elements with delay

前端 未结 8 1888
星月不相逢
星月不相逢 2021-01-06 18:50

I have an arrays=[John; Alex; Mark], I wanna to show the elements of this array one by one by 3 second delay.

for (var i=0; i<=3; i++)
  {
          


        
相关标签:
8条回答
  • 2021-01-06 19:16

    http://jsfiddle.net/rlemon/mHQVz/1/

    I got to tinkering... albeit this is probably not the best solution it was fun.

    var x = document.getElementById('x'),
        s = ['John', 'Mark', 'Alex'];
    
    (function loop() {
        s.length && (x.innerHTML = s.shift(), setTimeout(loop, 3000));
    })();
    

    Alnitak's solution is alot better. However they both would work (his is just more readable and less hacky also does not destroy the array).

    0 讨论(0)
  • 2021-01-06 19:18

    Try this without pseudo-recursion

    var arr = [10,20,30,40]; // your array
    var i = 0;
    var interval = 2000 // 2 sec, you can add your time required
    function callInterval() {
    // set a variable for setInterval
    	var time = setInterval(()=>{
    		console.log('['+arr[i]+','+i+']');
    		i++; 
    		if(i==arr.length){
    			this.clearInterval(time);// clear the interval after the index
    		}
    		}, interval);
    }
    
    callInterval();

    0 讨论(0)
提交回复
热议问题