Skip to content

Debounce async functions and reject or resolve, as promised :)

Notifications You must be signed in to change notification settings

therootcompany/debounce.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Debounce async functions and reject or resolve, as promised :)

Usage

let delay = 300; // ms

let doStuff = Debouncer.create(function (x) {
  console.log("Finally!", x);
}, 300);

doStuff("a"); // debounced
doStuff("b"); // debounced
doStuff("c"); // "Finally! c" (after 300ms)

Features

  • Rejects when
    • the call is debounced (due to a subsequent call)
    • your function has not yet resolved (it's still in progress)
    • your function rejects (or throws)
  • Resolves when
    • the call is not debounced AND your function resolves

Install

Browser

<script src="https://unpkg.com/@root/debounce"></script>

Or

<script src="https://unpkg.com/@root/debounce@v1.0.1/debounce.min.js"></script>
var Debouncer = window.Debouncer;
Debouncer.create(fn, ms);

Node.js / WebPack

# node.js
npm install --save @root/debounce
var Debouncer = require("@root/debounce");
Debouncer.create(fn, ms);

Example

async function doStuff() {
  console.log("Doing important things...");
  await sleep(100);
  console.log("Did important things!");
}

let doStuffDebounced = Debouncer.create(doStuff, 300);

doStuffDebounced(); // rejected
doStuffDebounced(); // rejected
doStuffDebounced(); // succeeds
setTimeout(function () {
  // rejected because doStuff is running
  doStuffDebounced();
}, 400);
setTimeout(function () {
  // succeeds because doStuff has finished and there's nothing to cancel it
  doStuffDebounced();
}, 600);
// helper
async function sleep(delay) {
  return new Promise(function (resolve, reject) {
    setTimeout(resolve, delay);
  });
}

About

Debounce async functions and reject or resolve, as promised :)

Resources

Stars

Watchers

Forks

Packages

No packages published