1.0.1 • Published 3 years ago

@root/debounce v1.0.1

Weekly downloads
-
License
MPL-2.0
Repository
github
Last release
3 years ago

debounce.js

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

Usage

// Usage
Debouncer.create(fn, delay);

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);
  });
}
1.0.1

3 years ago

1.0.0

3 years ago