Skip to content

Instantly share code, notes, and snippets.

@rmkane
Last active August 29, 2015 14:08
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rmkane/c788970604a47b845494 to your computer and use it in GitHub Desktop.
Timer and TimerTask written using the MooTools framework.

#MooTools Timer Example

Below is a code snippet that uses the Timer and TimerTask classes.

##Script

function print(id, value) {
    document.getElementById(id).innerHTML = value;
}

var i = 0;
var t1 = new Timer({
    delay: 100,
    tasks: [
    new TimerTask({
        run: function () {
            print('output1', String.fromCharCode(65 + i));
        },
        onComplete: function () {
            console.log('Task 1 complete...');
        },
        counter: 26
    }),
    new TimerTask({
        run: function () {
            print('output2', parseInt(i++, 10));
        }
    })]
});

t1.start();

// After 4 seconds, stop all timers.
setTimeout(function() {
    Timer.stop();
}, 5000);

##Document

<html>
    <body>
        <div id="output1"></div>
        <div id="output1"></div>
    </body>
</html>
/**
* Based off of https://gist.github.com/NV/363465#file-timer-js
*/
var Timer = new Class({
initialize: function (options) {
this.id = 0;
this.running = true;
this.count = 0;
this.delay = options.delay || 1000;
this.tasks = options.tasks || [];
Timer.all.push(this);
},
start: function () {
var me = this;
me.id = setInterval(function tick() {
if (!me.running) return;
for (var i = 0; i < me.tasks.length; i++) {
var task = me.tasks[i];
if (task.isActive()) {
task.execute();
}
}
me.count++;
}, this.delay);
},
pause: function pause() {
this.running = false;
return this;
},
run: function run() {
this.running = true;
return this;
},
stop: function stop() {
clearInterval(this.id);
this.stopped = true;
return this;
},
schedule: function (task) {
this.tasks.push(task);
}
});
Timer.extend({
all : [],
pause : function pause() {
var all = Timer.all;
for (var i = 0; i < all.length; i++) {
all[i].pause();
}
return all;
},
run : function run() {
var all = Timer.all;
for (var i = 0; i < all.length; i++) {
all[i].run();
}
return all;
},
stop : function stop() {
var all = Timer.all;
for (var i = 0; i < all.length; i++) {
all[i].stop();
}
return all;
}
});
var TimerTask = new Class({
initialize: function (options) {
this.counter = options.counter || 0;
this.run = options.run;
this.onComplete = options.onComplete;
this.active = true;
this.isInfinite = this.counter === 0;
},
execute: function () {
if (!this.isInfinite && this.counter === 0) {
this.active = false;
if (this.onComplete !== undefined) {
this.onComplete();
}
} else {
this.run();
if (!this.isInfinite) {
this.counter--;
}
}
},
isActive: function () {
return this.active;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment