I'm currently writing a web application that needs all the elements in the <body> tag to be added into the page one by one, at regular intervals. The elements first need to be removed from the page, then put in setTimeout() functions at regular intervals to add them back in. Here's what I have so far:
window.onload = function() {
var body = document.getElementsByTagName("body")[0];
var time = 0;
for (var i = body.children.length - 1; i > 0; i--) {
var element = body.children[i]; // get element
body.removeChild(element); // remove element from page
window.setTimeout(function() { // in [time] seconds, add element back into page
body.appendChild(element);
}, time);
time += 5000; // five seconds between elements going into the page
}
}
For some reason, this only adds in the first two elements, and the rest are ignored. I think it might be an issue with storing element in a setTimeout() call, but I'm not quite sure. Is there a better way to do this?
You need
i <= 0, because you are skipping over the last child (the first element when looping backwards).If you want to loop forwards, change the way you set your duration.