1.0.0 • Published 6 months ago

my-sleep-package v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

my-sleep-package

A lightweight utility to handle asynchronous timing in JavaScript, including:

  • A sleep (delay) function
  • A retry mechanism with optional delays
  • An exponential backoff function

Works in both Node.js and browsers.

Installation

npm install my-sleep-package

Usage

  1. Sleep
const { sleep } = require('my-sleep-package');

(async () => {
  console.log('Start');
  await sleep(2000); // Wait 2 seconds
  console.log('After 2 seconds');
})();
  1. Retry
const { retry } = require('my-sleep-package');

async function fetchData() {
  // Replace this with any async logic you want
  // For example, a fetch or axios call
  throw new Error('Simulated error');
}

retry(fetchData, 3, 1000)
  .then(result => {
    console.log('Success:', result);
  })
  .catch(error => {
    console.error('Failed after 3 attempts:', error);
  });
  1. Backoff
const { backoff } = require('my-sleep-package');

async function unstableApiCall() {
  // Replace with your real API call
  throw new Error('Transient network error');
}

// Try up to 5 times with an exponential delay based on 500 ms base delay
backoff(unstableApiCall, 5, 500)
  .then(result => {
    console.log('Success:', result);
  })
  .catch(error => {
    console.error('Failed after 5 attempts:', error);
  });

Why Use This Package?

Lightweight: Only a few lines of code. No Dependencies: Minimizes bundle size. Common Use-Cases: Sleep, retry, and backoff are everyday needs in async code. Easy: Simple functions, no configuration overhead. License MIT

1.0.0

6 months ago