You can use setTimeout()
to walk through the sequence, removing one and adding another on each timer call until you get to the end of the array:
(function() {
var cntr = 0;
var lastItem;
function next() {
if (lastItem) {
lastItem.parentNode.removeChild(lastItem);
lastItem = null;
}
if (cntr < seqIDs.length) {
var newDiv = document.createElement("div");
document.getElementById(seqIDs[cntr++]).appendChild(newDiv);
lastItem = newDiv;
setTimeout(next, 1000);
}
}
next();
})();
If you want it to just repeat itself over and over again, you can put it in a function that takes an argument for whether to repeat itself and then wrap cntr
back to 0
:
function cycleDiv(forever) {
var cntr = 0;
var lastItem;
function next() {
if (lastItem) {
lastItem.parentNode.removeChild(lastItem);
lastItem = null;
}
if (forever && cntr >= seqIDs.length) {
// wrap back to zero
cntr = 0;
}
if (cntr < seqIDs.length) {
var newDiv = document.createElement("div");
document.getElementById(seqIDs[cntr++]).appendChild(newDiv);
lastItem = newDiv;
setTimeout(next, 1000);
}
}
next();
}
cycleDiv(true);
To make one that you can start or stop at any time, you could do this:
function cycleDiv(forever) {
var cntr = 0;
var lastItem;
function next() {
if (lastItem) {
lastItem.parentNode.removeChild(lastItem);
lastItem = null;
}
if (forever && cntr >= seqIDs.length) {
// wrap back to zero
cntr = 0;
}
if (cntr < seqIDs.length) {
var newDiv = document.createElement("div");
document.getElementById(seqIDs[cntr++]).appendChild(newDiv);
lastItem = newDiv;
this.timer = setTimeout(next, 1000);
}
}
this.stop = function() {
clearTimeout(this.timer);
this.timer = null;
}
this.start = function() {
if (!this.timer) {
next();
}
}
}
var cycler = new cycleDiv(true);
cycler.start();
// then some time later
cycler.stop();
Also, it's a bit inefficient to keep creating and removing a new div element every second. I don't know what you're doing with the content of this div (since there's nothing in it in this code), but you could just have one div that you move from one parent to the next rather than continually making new div elements.