Mootools IntervalController mixin

javascript mixin mootools programming

How many times do you need to implement a functionality which has to be run every n seconds and possibly should be stopped and resumed? Not so often probably but it happens and happened to me just today, for this reason I decided to write a mootools Mixin so that I can reuse this code when I need it.

The code

* IntervalController Mixin
* Provides methods to start, stop and resume
* a setInterval functionality
var IntervalController = new Class({
  _started: false,
  _handler: null,
  _callback: null,
  _interval: null,
  startInterval: function(callback, interval) {
    this._callback = callback;
    this._interval = interval;
    this._handler = setInterval(callback, interval);
    this._started = true;
  stopInterval: function() {
    if(this._handler === null) {
      console.log("nothing to stop");
    else {
      this._handler = null;
  resumeInterval: function() {
    if(!this._started) {
      console.log("not yet started");
    else if(this._handler !== null) {
      console.log("already running");
    else {
      this._handler = setInterval(this._callback, this._interval);

The mixin provides three public methods.

(void) startInterval(callback, interval)

callback: the function to be called every interval ms.

interval: the loop interval.

Starts the loop invoking the js setInterval then stores its handler and the passed parameters.

(void) stopInterval()

Stops the loop.

(void) resumeInterval()

Resumes the loop using the previously stored parameters.

How to use it

Now it's time to use our new mixin, fortunately it's quite simple, just pass it to the implement mutator (as the Options extra class) and all its methods become available in your class.

var MyClass= new Class({
  Implements: [IntervalController],
  initialize: function() {
    // here you may use the startInterval, stopInterval and resumeInterval methods

You may see the mixin in action in a "Bounce Showcase" widget I've posted on codepen.

view demo

Subscribe to abidibo.net!

If you want to stay up to date with new contents published on this blog, then just enter your email address, and you will receive blog updates! You can set you preferences and decide to receive emails only when articles are posted regarding a precise topic.

I promise, you'll never receive spam or advertising of any kind from this subscription, just content updates.

Subscribe to this blog

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!