The defer(fn, options) function transforms a named function into a background function.

Example:

import { defer } from "@defer/client";

const sayHello = async (name: string) => console.log(`hello ${name}!`);

export default defer(sayHello);

Options

retry
boolean | integer | object

Determines what happens when this function fails. By default, retry is false, meaning the scheduler won’t re-execute the function.

When set to true the default configuration is applied:

{
 maxAttempts: 13,
 initialInterval: 30,
 randomizationFactor: 0.5,
 multiplier: 1.5,
 maxInterval: 60 * 10,
}

When set to ‘integer’ (e.g. 3), the default configuration is applied but with a custom maxAttempts:

{
 maxAttempts: 3,
 initialInterval: 30,
 randomizationFactor: 0.5,
 multiplier: 1.5,
 maxInterval: 60 * 10,
}

When set to “object”, the specified configuration is applied. The object is defined as follows:

  • maxAttempts: How many retries should we attempt in total.
  • initialInterval: How close the first retry should be? (in seconds).
  • randomizationFactor: How much randomness should be introduced in the space between retries.
  • multiplier: How fast the space between each retry should grow? (exponential back-off).
  • maxInterval: What should be the max space between 2 retries? (in seconds).

Examples:

export default defer(sayHello, { retry: true });
concurrency
integer

Determines the maximum number of parallel executions that are allowed for this function. There is no limit on concurrency by default.

Examples:

export default defer(sayHello, { concurrency: 1 });
maxDuration
integer

Determines the maximum allowed execution duration in second for this function, with a default of 30 minutes.

Examples:

export default defer(sayHello, { maxDuration: 5 * 60 });
maxConcurrencyAction
"cancel" | "keep"

Determines the action to take on next execution in queue when the concurrency limit is already reached for the function (i.e. N executions are running, where N is the concurrency of the function).

Available starting version 1.15.0

Examples:

export default defer(sayHello, { concurrency: 1, maxConcurrencyAction: 'cancel' });