Skip to content
Myr

jspec.timers.js

This file

Path

spec/lib/jspec.timers.js

90 lines · 1.8 KiB · JavaScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 5342d04 point at it.

Docsvisionmediabefore adoption5342d04

lines 1–90why, one step back
1
2// Mock Timers - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34;(function(){5 6 /**7 * Version.8 */9 10 mockTimersVersion = '1.0.2'11 12 /**13 * Localized timer stack.14 */15 16 var timers = []17 18 /**19 * Set mock timeout with _callback_ and timeout of _ms_.20 *21 * @param {function} callback22 * @param {int} ms23 * @return {int}24 * @api public25 */26 27 setTimeout = function(callback, ms) {28 var id29 return id = setInterval(function(){30 callback()31 clearInterval(id)32 }, ms)33 }34 35 /**36 * Set mock interval with _callback_ and interval of _ms_.37 *38 * @param {function} callback39 * @param {int} ms40 * @return {int}41 * @api public42 */4344 setInterval = function(callback, ms) {45 callback.step = ms, callback.current = callback.last = 046 return timers[timers.length] = callback, timers.length47 }48 49 /**50 * Destroy timer with _id_.51 *52 * @param {int} id53 * @return {bool}54 * @api public55 */5657 clearInterval = clearTimeout = function(id) {58 return delete timers[--id]59 }60 61 /**62 * Reset timers.63 *64 * @return {array}65 * @api public66 */67 68 resetTimers = function() {69 return timers = []70 }71 72 /**73 * Increment each timers internal clock by _ms_.74 *75 * @param {int} ms76 * @api public77 */78 79 tick = function(ms) {80 for (var i = 0, len = timers.length; i < len; ++i)81 if (timers[i] && (timers[i].current += ms))82 if (timers[i].current - timers[i].last >= timers[i].step) {83 var times = Math.floor((timers[i].current - timers[i].last) / timers[i].step)84 var remainder = (timers[i].current - timers[i].last) % timers[i].step85 timers[i].last = timers[i].current - remainder86 while (times-- && timers[i]) timers[i]()87 }88 }89 90})()