Bare-bones animation-friendly cancelable timeouts via requestAnimationFrame
Provides the familiarity of
setTimeout, but via
Deferred callbacks can be fired immediately or killed.
See "usage" below.
Important to consider
requestAnimationFrame approach means your callbacks will likely not fire exactly when you originally instructed.
If things are running at a smooth 60fps, callbacks should generally fire within 16ms of being told to.
Run the tests to see typical results.
Install via npm.
$ npm i timeout-raf
Require the module - it exposes a single factory function (so there's no need to instantiate instances).
Call as you would
window.setTimeout, passing a callback and duration.
var timeout = ;// typical usage; console.log is called after 1s;
Passing context as a parameter
You can pass context via an optional third parameter, allowing you to define the context of the callback.
var awesomeObject = awesome: 'clearly';// logs `clearly` after (about) 1 second;
Passing context normally
You can also pass context per usual by binding the callback to any object.
var awesomeObject = awesome: 'clearly';// also logs `clearly` after (about) 1 second;
Killing a timeout
Keep a reference to the timeout and then call its
kill() method to prevent it from ever firing its callback.
// never writes to the console...var to =;to;
You can tell a timeout to fire its callback at any time earlier than originally requested.
Keep a reference to the timeout and call its
fire method if you get antsy.
The callback will fire immediately, and never again.
// fired after 1 second and never againvar to =;;
Tests can be run in-browser via