Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

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.