The central timer model has a single setTimeout being used to control the updating of an array of objects. In this case Flyer objects, divs with text, have their position updated.
The individual timer model uses a setTimeout for each object. They update themselves.
To show that the different methods are being used, the Flyers show which timer is controlling them, although they only update the display every so often.
var centralTimer = 0;
function intBetween(a, b) {
return Math.floor(Math.random() * (b - a + 1)) + a;
}
function Flyer() {
this.div = document.createElement("div");
this.div.innerHTML = "Flyer!";
this.div.className = "flyer";
this.x = intBetween(50, 300);
this.y = intBetween(50, 700);
this.vx = intBetween(-6, 5) + 0.5;
this.vy = intBetween(-6, 5) + 0.5;
this.step = 0;
}
Flyer.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > 500) this.vx *= -1;
if (this.y < 0 || this.y > 800) this.vy *= -1;
this.div.style.left = this.x + "px";
this.div.style.top = this.y + "px";
if (this.step == 100) {
this.div.innerHTML = (centralTimer == 0) ? this.timer : centralTimer;
this.step = 0;
}
this.step++;
}
function init(central) {
clearTimeout(centralTimer);
centralTimer = 0;
var mainDiv = document.getElementById("main");
while (mainDiv.firstChild) {
mainDiv.removeChild(mainDiv.firstChild);
}
var flyers = [];
var numFlyers = 500;
for (var i = 0; i < numFlyers; i++) {
(function() {
var curFlyer = new Flyer();
mainDiv.appendChild(curFlyer.div);
if (!central) {
setTimeout(function() {
curFlyer.update();
curFlyer.timer = setTimeout(arguments.callee, 10);
}, 10);
}
flyers[i] = curFlyer;
})();
}
if (central) {
setTimeout(function() {
for (var i = 0; i < flyers.length; i++) {
flyers[i].update();
}
centralTimer = setTimeout(arguments.callee, 10);
}, 10);
}
}
window.onload = function() {
document.getElementById("btnCentral").onclick = function() {init(true)};
document.getElementById("btnEach").onclick = function() {init(false)};
};