// Timer implementation that reduces setTimeout/clearTimeout calls. // NOTE: something worse accuracy in not WebKit browsers (JS time accuracy). var Timer = (function( G ) { return function Timer( g ) { g = g || G; var noargs = [], Date = g.Date, now = Date.now || function(){ return +new Date(); }, timer_id, end_time, callback, context, args; function onTimeout() { var dt = end_time - now(); if ( dt > 0 ) { timer_id = g.setTimeout( onTimeout, dt ); } else { var _callback = callback, _context = context, _args = args; timer_id = callback = context = args = 0; _callback.apply( _context, _args || noargs ); } } return { set: function( delay, _callback, _context, _args ) { var t = end_time; end_time = now() + delay; callback = _callback; context = _context; args = _args; if ( !timer_id || end_time < t ) { timer_id && g.clearTimeout( timer_id ); timer_id = g.setTimeout( onTimeout, delay ); } return this; }, clear: function() { if ( timer_id ) { g.clearTimeout( timer_id ); timer_id = callback = context = args = 0; } return this; } }; }; })( this );