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

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.