Goodbye!
Hello!

Central control for timers

Concept courtesy of John Resig and can be found in his new book "Secrets of the JavaScript Ninja". Do it again

Advantages of Central timer control:
      var timers = {                  //#1 Declare timer control object

        timerID: 0,                   //#2 Record state
        timers: [],                   //#2

        add: function(fn) {           //#3 Create function to add handlers
          this.timers.push(fn);
        },

        start: function runNext() {  //#4 Function to start a timer
          if (this.timerID) return;
          (function() {
            if (timers.timers.length > 0) {
              for (var i = 0; i < timers.timers.length; i++) {
                if (timers.timers[i]() === false) {
                  timers.timers.splice(i,1);
                  i--;
                }
              }
              timers.timerID = setTimeout(runNext, 0);
            }
          })();
        },

        stop: function() {         //#5 Clear timeout - stop function
          clearTimeout(this.timerID);
          this.timerID = 0;
        }

      };

      var box = document.getElementById("box"), x = 0, y = 20;
      var square = document.getElementById("square"), x = 0, y = 0;

      timers.add(function() {
        box.style.left = x + "px";
        if (++x > 90) return false;
      });

      timers.add(function() {
        box.style.top = y + "px";
		y += 2;
        if (y > 200) return false;
      });
	  
	 timers.add(function() {
        square.style.left = x + "px";
        if (++x > 100){
			square.style.background = "yellow";			
		 return false;
		}
      });

      timers.start();