Giter VIP home page Giter VIP logo

debounce's Introduction

debounce

Delay function calls until a set time elapses after the last invocation

Install

npm install debounce

Usage

import debounce from 'debounce';

function resize() {
	console.log('height', window.innerHeight);
	console.log('width', window.innerWidth);
}

window.onresize = debounce(resize, 200);

(You can also use const debounce = require('debounce'))

To later clear the timer and cancel currently scheduled executions:

window.onresize.clear();

To execute any pending invocations and reset the timer:

window.onresize.flush();

API

debounce(fn, wait, options?)

Creates a debounced function that delays execution until wait milliseconds have passed since its last invocation.

Set the immediate option to true to invoke the function immediately at the start of the wait interval, preventing issues such as double-clicks on a button.

The returned function has a .clear() method to cancel scheduled executions, and a .flush() method for immediate execution and resetting the timer for future calls.

Related

  • p-debounce - Similar but handles promises
  • throttleit - Throttle a function to limit its execution rate

debounce's People

Contributors

aaronbeall avatar billymoon avatar juliangruber avatar matthewmueller avatar p avatar rigwild avatar selbekk avatar sindresorhus avatar stephenmathieson avatar suhaotian avatar tj avatar tootallnate avatar tylerhou avatar vendethiel 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

debounce's Issues

Allow injecting a custom setTimeout?

Hardcoding this to always use the global setTimeout is problematic. In most unit testing frameworks, there's no way to programmatically skip forward to the execution time - we'd have to also setTimeout in the tests.

Proposal: allow debounce method to take in an object containing the settings, as it's starting to accept quite a few. What if we want to specify wait and setTimeout but not immediate?

debounce and throttle seems to decrease performance for window.onscroll

Hi,

Using this package or throttle I have done some tests in Firefox and I have noticed using either package (yours or theirs) for throttling or debouncing a window.onscroll function is worse then just allowing the function to run on every pixel scroll.

I wouldnt have thought this because i thought the debounce would prevent any operations from happening but it seems the operations the debounce does to debounce operations from happening is more expensive then the operations just happening.

It seems in firefox on every metric they measure says using debounce or throttle for onscroll is worse for performance.

Does anyone have anything to weigh in on this?
I am not a performance measuring pro.

Allow ES-style import { debounce } from "debounce"?

As this module works now, it violates ES6/ES2015-style module export rules. See this SO question and answer for why TypeScript cares and this bug on DefinitelyTyped for additional reasoning why it's inconvenient to users.

To not break the existing const debounce = require("debounce"); for users, I propose the object be given a .debounce member so we can also import it using const { debounce } = require("debounce"); (or var debounce = require("debounce").debounce; for the traditional folks).

Run debounce() callback if browser tab is closed

This is a very common problem with debounced API calls: when the user closes the browser tab, the debounced function may not have run yet. This is a frequent cause of data loss. The _.debounce() function should avoid this issue by running the trailing debounce immediately if the tab is closed prior to the trailing timeout. This should only happen while running inside a browser because it's not relevant in headless runtimes (e.g. Node.js).

Add support for promises

debounce is an async function by definition and it doesn't have a callback or any sort of completion handler. This makes it hard to test and use with promises or any I/O.

We should at at least return a promise.

debounce(mything, 100)()
  .then(() => console.log('done after 1s!'))

This is not a breaking change even. Phase two would be to just proxy what mything returns through the promise chain and being able to .catch

debounce(mything, 100)()
  .then(() => console.log('done after 1s!'))
  .catch((err) => console.log('failed after 1s!: %s', err.message))

where

function mything() {
  return Promise.resolve('something')
}

Provide a way to cancel scheduled debounces

I think the wrapped function should have a clear method attached to clear any scheduled debounce:

var debounced = debounce(fn, 300);

debounced();
debounced();
debounced.clear();

Proper testing

This module really needs proper tests. I see mocha being installed but it's not used anywhere and test.html can barely be classified as a test.

Protect against improper use

I've seen people use debounce to do this:

function MyClass() {}

MyClass.prototype.debounced = debounce(function () {
 // ...
});

This can lead to really confusing problems if they create multiple instances of MyClass.

In this case:

var c1 = new MyClass();
var c2 = new MyClass();

c1.debounced('a');
c2.debounced('b');

This leads to the method only ever being called on c2 with arguments "b". It is almost certainly not what the user intended.

I think it's fairly easy to catch that misuse here: index.js#L41

I think the solution is to compare context to previously set values. If it changes, then throw

if (context && this !== context) {
  // If people feel an Error is to strong, maybe just log a warning?
  throw new Error('debounced method called with different contexts');
}

Happy to create a PR if anyone is still maintaining this.

arguments get reset if you call debounced function within itself

Summary

๐Ÿ‘‹ Hi there! I've noticed that calling a debounced function from itself sets its arguments to undefined.

Minimal working example

debounce = require('debounce');

const func = debounce((x) => {
  console.log(x);
  func(2);
}, 1000);

func(1);

Actual output

1
undefined
undefined
undefined
// ...

Expected output

1
2
2
2
// ...

Workaround

As a temporary workaround, I can defer the call:

  setTimeout(() => func(2));

Cause

https://github.com/component/debounce/blob/master/index.js#L27-L28

result = func.apply(context, args); // calls debounced function, which sets args
context = args = null; // args gets reset here

Debounced function executing early?

Hey guys

I have a debounced function that sometimes executes the debounced function early (before fully waiting). I am calling the debounced function many times a second and was thinking maybe one reason it was executing early was because if the debounced function was called twice within the same millisecond, this line would execute the debounced function.

Is this a possible explanation? What is the rationale behind the last > 0 condition on the if statement on that line?

Thanks!

Bob

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.