The IdleValue
class is a helper that allows developers to implement the idle-until-urgent pattern in their code. It's useful when you want to initialize a value during an idle period but ensure it can be initialized immediately as soon as it's needed.
import {IdleValue} from 'idlize/IdleValue.mjs';
class MyClass {
constructor() {
// Create an IdleValue instance for `this.data`. It's value is
// initialized in an idle callback (or immediately as soon as
// `this.data.getValue()` is called).
this.data = new IdleValue(() => {
// Run expensive code and return the result...
});
}
}
Name | Description |
---|---|
constructor(init) |
Parameters:
The initialization function is scheduled to run in an idle callback as soon as the instance is created. |
getValue() |
Returns: (*) Returns the value returned by the initialization function passed to the constructor. If the initialization function has already been run, the value is returned immediately. If the initialization function is still scheduled for an idle callback, that callback is cancelled, the initialization function is run synchronously, and the result is returned. |
setValue(newValue) |
Parameters:
Assigns a new value. If the initialization function passed to the constructor has not yet run, it is cancelled. |