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
4 Answers
Reset to default 5I 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)