Skip to content

Instantly share code, notes, and snippets.

@Williammer
Created June 18, 2014 07:21
Show Gist options
  • Save Williammer/2ca3fa2b25d48758bc7d to your computer and use it in GitHub Desktop.
Save Williammer/2ca3fa2b25d48758bc7d to your computer and use it in GitHub Desktop.
jsTimer.centralTimerControl.html - implemented a timer that execute certain action and manage threads.
<body> < div id = "box" style = "position:relative;display:inline;" > Bird! </div>
</body>
<script>
var timers = {
timerID: 0,
timers: [],
add: function (fn) {
this.timers.push(fn);
},
start: function () {
if (this.timerID) return;
(function runNext() {
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 () {
clearTimeout(this.timerID);
this.timerID = 0;
}
};
var box = document.getElementById("box"),
x = 200,
y = 0;
timers.add(function () {
box.style.left = x + "px";
if (++x > 1200) return false;
});
timers.add(function () {
box.style.top = y + "px";
y += 2;
if (y > 500) return false;
});
timers.start();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment