Skip to content

Instantly share code, notes, and snippets.

@ruzz311
Created August 30, 2012 17:11
Show Gist options
  • Save ruzz311/3533722 to your computer and use it in GitHub Desktop.
Save ruzz311/3533722 to your computer and use it in GitHub Desktop.
Timer.js - AMD module used for accurate, long timers
define([
"namespace",
// Libs
"use!jquery",
"use!backbone"
// Modules
// Plugins
],
function( namespace, $, Backbone ) {
// Create a new module
var Timer = namespace.module(),
app = namespace.app;
var defaults = {
"length" : 5000,
"resolution" : 20,
"ontick": function(){},
"oncomplete": function(){}
}
// =============================================================== Start
// see http://www.sitepoint.com/creating-accurate-timers-in-javascript/ for inspiration
Timer.start = function ( options ){
var length = options.length || defaults.length,
resolution = options.resolution || defaults.resolution,
ontick = options.ontick || defaults.ontick,
oncomplete = options.oncomplete || defaults.oncomplete;
var steps = ( length / 100 ) * ( resolution / 10 ),
speed = length / steps,
count = 0,
start = new Date().getTime();
function tick(){
if( count++ == steps ){
oncomplete( steps, count );
} else {
ontick( steps, count );
var diff = ( new Date().getTime() - start ) - ( count * speed );
window.setTimeout( tick, ( speed - diff ) );
}
}
window.setTimeout( tick, speed );
}
// ============================================================================== VIEWS
return Timer;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment