timer-shim

raw JSON →
0.3.0 verified Sat Apr 25 auth: no javascript abandoned

Timer-shim is a lightweight wrapper around setTimeout, setInterval, and clearTimeout/clearInterval that facilitates testing time-dependent code without modifying global state. It provides multiple aliases (e.g., timer.timeout, timer.to, timer.t) for convenience and validates arguments against NaN and non-function values. Version 0.3.0 is stable but appears unmaintained (last release 2012). Unlike sinon's fake timers, timer-shim only stubs calls without advancing time. Its key differentiator is simplicity and avoidance of global overrides, making it suitable for isolated unit tests.

error TypeError: timer.timeout is not a function
cause Importing the package incorrectly (e.g., using ES6 import in a CommonJS project) or the package was not installed.
fix
Ensure the package is installed and use require('timer-shim'). For ES6, use const timer = require('timer-shim');
error timer.clear is not a function
cause Attempting to call timer.clear before the module is fully loaded or using a different variable name.
fix
Verify the require statement: const timer = require('timer-shim'); then call timer.clear(handle);
error ReferenceError: timer is not defined
cause The timer variable was not declared or scoped incorrectly.
fix
Add: const timer = require('timer-shim'); at the top of the file.
deprecated Package is unmaintained since 2012. No updates for over a decade.
fix Consider using sinon.useFakeTimers or lolex for modern timer testing.
gotcha Both argument orders (timeout, fn) and (fn, timeout) are supported. May confuse developers expecting strict order.
fix Be consistent: use (delay, function) to avoid ambiguity.
gotcha Package does not provide a TypeScript declaration file. No compile-time type checking.
fix Create a custom .d.ts file or use @ts-ignore.
gotcha timer.clear is aliased to clearTimeout; it does not handle interval handles separately. Both timeouts and intervals are cleared with the same function.
fix Use timer.clear for both, but note that it internally calls clearTimeout. Works for both since handles are just numbers.
npm install timer-shim
yarn add timer-shim
pnpm add timer-shim

Demonstrates basic usage of timer.interval and timer.timeout, then shows how to stub timer.timeout with sinon for testing.

const timer = require('timer-shim');
let count = 0;
const handle = timer.interval(50, () => {
  count++;
  console.log(count);
  if (count === 5) timer.clear(handle);
});
timer.timeout(200, () => console.log('done'));

// Stubbing example:
const sinon = require('sinon');
sinon.stub(timer, 'timeout').callsArg(1);
let internalState = false;
function testFn() {
  timer.timeout(100, () => { internalState = true; });
}
testFn();
console.log(internalState); // true (due to stub)
timer.timeout.restore();