Created
August 30, 2012 17:11
-
-
Save ruzz311/3533722 to your computer and use it in GitHub Desktop.
Timer.js - AMD module used for accurate, long timers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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