Reputation: 748
I'm trying to create a loop in JS that is every second changing / rotating positions of N elements in array in a way that first becomes second, second becomes third, and so on, last becomes first and when is over repeat it again
first step
array = ['1','2','3'];
second step
array = ['2','3','1'];
third step
array = ['3','1','2'];
repeat
it seems quite easy but I'm stuck
thanks
Upvotes: 2
Views: 814
Reputation: 13953
Array.shift()
will remove the first element. Array.push()
will add the element at the end
setInterval
will execute the function every 1000
ms
let array = [1,2,3];
setInterval(()=>{
array.push(array.shift());
console.log(JSON.stringify(array));
}, 1000);
Upvotes: 7
Reputation: 6459
very simple
//ES5
var array = ['1','2','3'];
function rotate(){
setInterval(function(){
console.log(array);
array.push(array.shift())
},1000)
}
rotate();
Upvotes: 3