Unjank
unjank
is an asynchronous Array.prototype.map
that doesn't lock up the browser's UI.
- Quickly learns how expensive it is to perform each task
- Runs the task in batches to acheive a target FPS
- Allows you to abort at any time
// Simulate an expensive function that takes 4ms to execute { } // Will only run expensiveFunction five times per frame to acheive 30 FPS
API
unjank(data, map, [opts], cb)
- data must be an array
- map can either be:
function sync (item) { return transform(item) }
function batchSync (batch) { return batch.map(transform) }
function async (item, cb) { cb(null, transform(item)) }
function batchAsync (batch, cb) { cb(null, batch.map(transform) }
- opts is an optional object
opts.targetFPS
defaults to 30opts.batchMap
defaults to false
- cb should have the signature
function cb(err, results, metadata) {}
err
if an async map function returns an error, this is where it goesresults
an array, just what you would expect fromarray.map
metadata
information learned byunjank
during executionmetadata.intervalPerItem
The average number of milliseconds eachmap(item)
tookmetadata.batchSize
The optimal number of items mapped per frame
Return Value
unjank
returns an instance object.
instance.completed
is true if the operation completed (and was not aborted)instance.aborted
is true if the operation was abortedinstance.abort
is a function you can call to abort the operation
Aborting
You can abort the task at any time by calling abort()
on the returned object.
var instance = instance
This will cause the callback function to be called with new Error('Aborted')
.
You cannot abort a task more than once, or once it has completed.
Async Example
var unjank = data = 1 2 3 4 5 6 { } // Ensure that each batch takes no longer than 32 ms to execute// in order to achieve 30FPS
Sync Example
var unjank = data = 1 2 3 4 5 6 { return item * 10 } // Ensure that each batch takes no longer than 16.6 ms to execute// in order to achieve 60FPS
Batch Mapping Example
Sometimes your task is best handled as a batch, instead of individually.
For example, you might want to render many Backbone views at the same time, but only append them to the DOM as a single DocumentFragment
. This is a very fast way to render a large collection.
With the batchMap
option set to true, unjank
will call your map function once per batch instead of once per item.
var unjank = async = data = 1 2 3 4 5 6 { } { async }