A small (376B) lazy function scheduler for a butter smooth main thread
Workshy is a throttle
utility that rate limit, queue, and distribute function executions over time to prevent the main thread from becoming unresponsive.
Unlike a standard throttle function, and to ensure non-blocking rendering and responsive UIs, workshy
break up functions into smaller chunks executed over time if necessary.
This module is available in three formats:
- ES Module:
dist/workshy.mjs
- CommonJS:
dist/workshy.js
- UMD:
dist/workshy.min.js
Install
$ npm install --save workshy
The script can also be directly included from unpkg.com:
Usage
; // dummy function doing heavy workconst greet = 'hello world'; // queue and call function;// => 'hello world' // tasks are only called once, but// multiple calls increases priorityconst a = ;const b = ;;;;// => A: 2// => B: 1 // manually define priorityconst func = ; // force it to be called immediatelyconst func = ; // workshy distribute the work over time to// make sure the main thread runs butter smoothfor let i = 0; i < 5000; i++ ; // => this won't block UI
API
workshy(task, [options])
Returns: function
task
Type: function
Accepts any function a returns a function
(a function that wraps your original function). Call returned function to queue task.
The returned function
will execute your function with the latest arguments provided to it as soon as possible based on queue length and prioroty.
Important: Task are only called once.
Calling the same task multiple times increases its priority.
options.priority
Type: Number
Default: 0
Tasks are sorted by priority. Functions with high priority are called first.
Important: Priority also increase if a task is called multiple times.
;//=> 'Hello World'
options.force
Type: Boolean
Default: false
;//=> 'Hello World'
Inspiration
This is inspired by the talk The Virtue of Laziness: Leveraging Incrementality for Faster Web UI
License
MIT © Terkel Gjervig