Skip to content
This repository has been archived by the owner on Jul 2, 2024. It is now read-only.

Latest commit

 

History

History
72 lines (60 loc) · 2.27 KB

IdleValue.md

File metadata and controls

72 lines (60 loc) · 2.27 KB

IdleValue.mjs

idlize/IdleValue.mjs

Overview

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.

Exports

Usage

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...
    });
  }
}

IdleValue

Methods

Name Description
constructor(init)

Parameters:

  • init (Function) An initialization function (typically something expensive to compute) that returns a value.

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:

  • newValue (*)

Assigns a new value. If the initialization function passed to the constructor has not yet run, it is cancelled.