Run a function in a Worker thread and get back a promise
npm install offload-fnimport offloadFunction from 'offload-fn';
const result = await offloadFunction((a, b) => a + b, 2, 3);
//=> 5
// CPU-intensive work
const sum = await offloadFunction(n => {
let total = 0;
for (let i = 0; i < n; i++) {
total += i;
}
return total;
}, 1_000_000);Returns a Promise that resolves with the function's return value.
Serializes the function to a string and runs it inside a Worker thread. Arguments and return values must be serializable via the structured clone algorithm.
Type: Function
The function to execute in a Worker thread.
Type: unknown[]
Arguments to pass to the function.
- The function cannot reference closure variables — it is serialized to a string.
- Arguments must be serializable (structured clone).
- The return value must be serializable (structured clone).
- perf-fn - Measure function execution time
MIT