DEV Community

Michael Di Prisco
Michael Di Prisco

Posted on

1

My Journey in Open Source - random-delay

What is this?

A library providing a parametrized random delay mechanism for functions (Both async and sync)

How do I install it?

You can install it by using the following command:

npm install random-delay
Enter fullscreen mode Exit fullscreen mode

How do I use it?

Both sync and async functions are supported.

The library provides a randomDelay function that takes 3 parameters:

  • minDelay: The minimum delay in milliseconds. Defaults to 0.
  • maxDelay: The maximum delay in milliseconds. Defaults to 1000.
  • method: The method to use. Can be either sync or async. Defaults to sync.

Sync

The library uses the event-loop-sleep library to sleep the event loop using SharedArrayBuffer and Atomics for sync functions.

const { randomDelay } = require('random-delay');

// Do something before...
randomDelay(1000, 2000, 'sync');
// Do something after...
Enter fullscreen mode Exit fullscreen mode

Async

The library uses a simple setTimeout (unrefed) for async functions.

const { randomDelay } = require('random-delay');

// Do something before...
await randomDelay(1000, 2000, 'async');
// Do something after...
Enter fullscreen mode Exit fullscreen mode

randomDelayed

The library also provides a randomDelayed, a higher-order function that takes 2 parameters:

  • fn: The function to wrap.
  • options: The options to pass to randomDelay. Defaults to the same as randomDelay.
const { randomDelayed } = require('random-delay');

// Do something before...
await randomDelayed(() => {
  // Do something
}, { minDelay: 1000, maxDelay: 2000, method: 'async' });
// Do something after...
Enter fullscreen mode Exit fullscreen mode

Tests

You can run the tests by using the following command:

npm test
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs