Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Loop
periodicTimeout = (callback, element, interval) ->
setTimeout(->
callback((new Date).getTime() + interval)
, interval)
class Loop
constructor: (@f = (->), @interval) ->
start: =>
return if @id
method = if @interval? then periodicTimeout else window.requestAnimationFrame
lastCallAt = undefined
(animLoop = (timestamp) =>
# https://developers.google.com/web/updates/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision
time = timestamp
if timestamp < 1e12
time = timestamp + performance.timing.navigationStart
return @stop() if @f(time, lastCallAt) is false
lastCallAt = time
@id = method(animLoop, undefined, @interval)
)()
this
stop: =>
return unless @id?
method = if @interval? then clearTimeout else cancelAnimationFrame
method(@id)
@id = undefined
this
@Loop = Loop
module?.exports = @Loop
var Loop, periodicTimeout,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
periodicTimeout = function(callback, element, interval) {
return setTimeout(function() {
return callback((new Date).getTime() + interval);
}, interval);
};
Loop = (function() {
function Loop(f, interval1) {
this.f = f != null ? f : (function() {});
this.interval = interval1;
this.stop = bind(this.stop, this);
this.start = bind(this.start, this);
}
Loop.prototype.start = function() {
var animLoop, lastCallAt, method;
if (this.id) {
return;
}
method = this.interval != null ? periodicTimeout : window.requestAnimationFrame;
lastCallAt = void 0;
(animLoop = (function(_this) {
return function(timestamp) {
var time;
time = timestamp;
if (timestamp < 1e12) {
time = timestamp + performance.timing.navigationStart;
}
if (_this.f(time, lastCallAt) === false) {
return _this.stop();
}
lastCallAt = time;
return _this.id = method(animLoop, void 0, _this.interval);
};
})(this))();
return this;
};
Loop.prototype.stop = function() {
var method;
if (this.id == null) {
return;
}
method = this.interval != null ? clearTimeout : cancelAnimationFrame;
method(this.id);
this.id = void 0;
return this;
};
return Loop;
})();
this.Loop = Loop;
if (typeof module !== "undefined" && module !== null) {
module.exports = this.Loop;
}
{
"name": "loop",
"version": "0.0.2",
"description": "",
"main": "loop.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://gist.github.com/3225993.git"
},
"author": "Antoine BERNIER",
"license": "ISC",
"bugs": {
"url": "https://gist.github.com/3225993"
},
"homepage": "https://gist.github.com/3225993"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment