Skip to content

Debounced versions of standard DOM events

License

Notifications You must be signed in to change notification settings

davekaro/debounced

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Debounced

Debounced versions of standard DOM events

This library uses event delegation to add debounced versions of standard bubbling DOM events.

Why?

Have you ever wired up event listeners for keyup, input, or mousemove? If so, you know that these events are dispatched frequently and often necessitate adding custom debounce functionality to your application.

What if you could simply listen for a debounced event instead? Now you can.

This technique pairs extremely well with libraries like Stimulus and StimulusReflex. Here are some simple examples.

<input type="text" data-controller="example" data-action="debounced:input->example#work">
<input type="text" data-reflex="debounced:input->Example#work">

Install

yarn add debounced

Basic Usage

import debounced from 'debounced'
debounced.initialize()
document.addEventListener('debounced:input', event => { ... })
document.getElementById('example').addEventListener('debounced:keydown', event => { ... })

Advanced Usage

By default we set up debounced events for all DOM events that bubble, but you can also specify which events you'd like debounced.

import debounced from 'debounced'

// debounce only the input event and wait 100ms before dispatching
debounced.initialize({ input: { wait: 100 } })

You can customize wait times for the default events.

import debounced from 'debounced'

// initialize default events but change the wait time for keyup
debounced.initialize({ ...debounced.events, keyup: { wait: 100 } })

You can also add debounced versions of custom events.

import debounced from 'debounced'

// initialize all default events and add some custom events
debounced.initialize({ ...debounced.events, "custom-event": { wait: 150 } })


// initialize a single custom event
debounced.initializeEvent('another-custom-event', { wait: 150 })

You can even change the prefix of the debounced event names.

debounced.initialize({ prefix: 'my-application', ...debounced.events })
document.addEventListener('my-application:input', event => { ... })

FAQ

  • What is the default wait time?

    200ms

  • Can I customize the wait time for an event type more than once?

    No, the setting used to initialize the event is global.

  • Does the debounced event run before or after the standard DOM event?

    After

About

Debounced versions of standard DOM events

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%