最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - remove first element in array after 10 seconds - Stack Overflow

programmeradmin0浏览0评论

I have a data of array which look like this:

myArray=['0','1','2','3','4','5'];

Now I want to remove the every first element of the array after 10 seconds. I am not asking for the plete code right now I just want to get some tips and suggestions on how to do that. Any answers are wele.

I have a data of array which look like this:

myArray=['0','1','2','3','4','5'];

Now I want to remove the every first element of the array after 10 seconds. I am not asking for the plete code right now I just want to get some tips and suggestions on how to do that. Any answers are wele.

Share Improve this question edited Apr 15, 2015 at 9:21 stuartd 73.4k16 gold badges138 silver badges168 bronze badges asked Apr 15, 2015 at 9:08 Lee LeeLee Lee 5836 gold badges14 silver badges28 bronze badges 3
  • 1 shift removes the first element from an array. It also returns that element, but if you don't want it you can just ignore that. – stuartd Commented Apr 15, 2015 at 9:11
  • 1 what do you want to do with the returned values - cut out the middle man - myArray=[];, or use SetInterval() – JMP Commented Apr 15, 2015 at 9:11
  • 1 you can use setInterval function to run after a interval and shift function to remove first element – v2solutions. Commented Apr 15, 2015 at 9:13
Add a ment  | 

4 Answers 4

Reset to default 5

I understand you want it to happen every 10 seconds because you've written "every first element".

var timer = window.setInterval(function () {
    if (myArray.length > 0)
        myArray.splice(0, 1);
    else
        window.clearInterval(timer);
}, 10 * 1000);

Or an even better solution as @Cerbrus suggested, by using Array.prototype.shift:

var timer = window.setInterval(function () {
    if (myArray.length > 0)
        myArray.shift();
    else
        window.clearInterval(timer);
}, 10 * 1000);

If you want it to happen only once, use window.setTimeout instead of window.setInterval:

var timer = window.setTimeout(function () {
    myArray.shift();
}, 10 * 1000);

You can do this:

setTimeout(function({
   var removedVariable = myArray.shift();
}), 10000)

Something like this should help:

http://jsfiddle/zho0ysgc/6/

 var arry = [1, 2, 3]
var count
alert(arry);

setTimeout (function(){ 
arry.shift();   
alert(arry);
}, 1000);

Removing first element in Array using jQuery 'shift' method, and printing in DOM Demo

myArray=['0','1','2','3','4','5'];            
    setInterval(function(){      
        if(myArray.length > 0) {
            $('.print').html(myArray.shift());    
        }    
    },1000)
发布评论

评论列表(0)

  1. 暂无评论