Coder Social home page Coder Social logo

ts-debounce's Introduction

TypeScript implementation of debounce function

Build Status npm npm bundle size (minified + gzip) npm type definitions

All Contributors

Debounce creates a new function g, which when called will delay the invocation of the original function f until n milliseconds, BUT drop previous pending delayed emissions if a new invocation is made before n milliseconds.

It's very useful for scenarios when it's better to limit the number of times the function is called. E.g. think of search input which fetches data from API. It's enough display search results after user has stopped entering characters for some time.

Install

You can install this package using npm using the command below

npm install ts-debounce

If you prefer yarn, install using the command below

yarn add ts-debounce

Function arguments

import { debounce } from "ts-debounce";

const debouncedFunction = debounce(originalFunction, waitMilliseconds, options);
  • originalFunction
    • the function which we want to debounce
  • waitMilliseconds
    • how many seconds must pass after most recent function call, for the original function to be called
  • options
    • isImmediate (boolean)
      • if set to true then originalFunction will be called immediately, but on subsequent calls of the debounced function original function won't be called, unless waitMilliseconds passed after last call
    • maxWait (number)
      • if defined it will call the originalFunction after maxWait time has passed, even if the debounced function is called in the meantime
        • e.g. if wait is set to 100 and maxWait to 200, then if the debounced function is called every 50ms, then the original function will be called after 200ms anyway
    • callback (function)
      • it is called when originalFunction is debounced and receives as first parameter returned data from originalFunction

Cancellation

The returned debounced function can be cancelled by calling cancel() on it.

const debouncedFunction = debounce(originalFunction, waitMilliseconds, options);

debouncedFunction.cancel();

Promises

Since v3 ts-debounce has Promise support. Everytime you call debounced function a promise is returned which will be resolved when the original function will be finally called. This promise will be rejected, if the debounced function will be cancelled.

You can also debounce a function f which returns a promise. The returned promise(s) will resolve (unless cancelled) with the return value of the original function.

const asyncFunction = async () => "value";
const g = debounce(asyncFunction);
const returnValue = await g();
returnValue === "value"; // true

Credits & inspiration

This implementation is based upon following sources:

Compability

  • version 3 - Promise must be available in the global namespace
  • version 2 - TypeScript 3.3
  • version 1 - TypeScript 2.0

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Zac

๐Ÿ’ป

Karol Majewski

๐Ÿ’ป

Fabien Rogeret

๐Ÿ’ป

Iman

๐Ÿ’ป

juanmendes

๐Ÿค”

sanduluca

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

ts-debounce's People

Contributors

achoarnold avatar allcontributors[bot] avatar chodorowicz avatar dependabot[bot] avatar iheidari avatar karol-majewski avatar meteorlxy avatar sanduluca avatar tony avatar tuizi avatar zacnomore avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ts-debounce's Issues

Request: add a max-wait option

Would it be possible to add a maxWait option like lodash does? This is helpful in situations where invocations of the function happen often enough that the callback never fires.

Promise should be optional.

Apologies if I've misinterpreted the documentation, but in V3 it seems that debounce now always returns a promise, no matter what. This breaks debounce in contexts where a Promise-wrapped result isn't expected, such as option parameters in 3rd-party libraries which expect a callback function. There should ideally be both a callback-based and a promise-based version of the function. I hope you don't mind the suggestion. Thanks!

Infer the argument that the debounced function is expected to take

For code like the following, the argument to the actual input handler is not inferred, it's any

document.querySelector('input').addEventListener(
  'input',
   // e here is any, should be Event
  debounce((e) => console.log('Typed text', e.target.value), 500)
);

However, it is possible to infer the type based on what it's being assigned to. As in, assigned to the 2nd parameter for addEventListener as above, or if you did something like the following:

// We can know that the type of a is string here
const lateLog: (s: string) => void = debounce((a) => console.log(a));

The following is an args inferring version of a much simpler debounce than you have implemented. Please ignore the return type of any, which is just used to minimize noise and focus on inferring the arguments.

function argInferringDebounce<Args extends unknown[]>(
  func: (...args: Args) => any,
  timeout = 300
): (...args: Args) => void {
  let timer: number;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, timeout);
  };
}

The idea is that you don't need to declare the entire (...args: any[]) => any; as a generic, or a Procedure as you have called it.

By moving the generic part just to the arguments of the function (<Args extends unknown[]>), this magical inference occurs.

Here's a stackblitz showing it in action

Missing declaration file on v0.3.3 ?

Hi.

It seems that [email protected] has no declaration file (.d.ts). ๐Ÿ˜“

Reproduction

// index.ts
import { debounce } from "ts-debounce";

debounce();
$ npx tsc index.ts --strict
index.ts:1:26 - error TS7016: Could not find a declaration file for module 'ts-debounce'. '/Users/koba/tmp/aaaaa/node_modules/ts-debounce/dist/src/index.js' implicitly has an 'any' type.
  Try `npm install @types/ts-debounce` if it exists or add a new declaration (.d.ts) file containing `declare module 'ts-debounce';`

1 import { debounce } from "ts-debounce";
                           ~~~~~~~~~~~~~

I would be glad if you would check this problem.

How can i cancel my debounce.

As a developer am using debounce function on filters.If i want to redirect to another page i want to cancel all the significant calls of debounce.

Same debounce function in multiple React components

I've noticed a very odd behaviour. I have different intances of react components (with different unique ids/keys) and these components/instances call the debounce function via a 'scroll' event listener. Maybe it's important to mention that the react components add the same event listener to the same (EXTERNAL = not within the react component) div element.
The problem is that when I scroll through the document, all of the react components/instances get the scroll event but ONLY ONE component/instances gets into the debounce function. This is difficult to debug for me but it seems that the react components share the same debounce function which I don't want.

Is this possible? And if yes, can I somehow make it so each react component instance has its own debounce function?

Node version incompatibilities?

Hey,

We are getting this issue on our CI when trying to yarn install with ts-debounce:

error [email protected]: The engine "node" is incompatible with this module. Expected version ">=8.*". Got "6.14.4"

Any idea?

Does not work with curried functions

Thank you for your wonderful library!

Steps to reproduce

const add = (x: number) => (y: number) => x + y;
const delayed = debounce(add, 1000);

delayed(2)(2);

Expected result

delayed returns 4 after at least a second.

Actual result

Console throws Uncaught TypeError: delayed(...) is not a function.

Maybe it would make sense to restrict function domain to procedures?

/**
 * A function that emits a side effect and does not return anything.
 */
export type Procedure = (...args: any[]) => void;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.