Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
67 lines (53 sloc) 1.92 KB

defineIdleProperty.mjs

idlize/defineIdleProperty.mjs

Overview

The module provides a defineIdleProperty helper function that allows developers to implement the idle-until-urgent pattern in their code. It's useful when you want to initialize a property value during an idle period but ensure it can be initialized immediately as soon as it's referenced.

Exports

Usage

import {defineIdleProperty} from 'idlize/defineIdleProperty.mjs';

class MyClass {
  constructor() {
    // Define a getter for `this.data` whose value is initialized
    // in an idle callback (or immediately if referenced).
    defineIdleProperty(this, 'data', () => {
      // Run expensive code and return the result...
    });
  }
}

defineIdleProperty

Syntax

defineIdleProperty(obj, prop, init);

Parameters

Name Type Description
obj Object The object on which to define the property.
prop string The name of the property.
init Function An function (typically something expensive to compute) that returns a value. The function is scheduled to run in an idle callback as soon as the property is defined. If the property is referenced before the function can be run in an idle callback, the idle callback is canceled, the function is run immediately, and the return value of the function is set as the value of the property.