Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Thedboun function is a utility designed to limit the rate at which a function is executed. It ensures that the provided function (fn) is called only after a specified delay (delay) has elapsed since the last invocation. By default, the delay is set to 400 milliseconds.

This is particularly useful for handling events that fire frequently, such as resizing, scrolling, or typing, by preventing the provided function from being called excessively.

Usage Example

Scenario: Search Input with Debounce

// Define the function to handle searchfunctionhandleSearch(query:string):void{console.log("Searching for:",query);}// Create a debounced version of the search handlerconstdebouncedSearch=dboun(handleSearch,300);// Simulate typing in a search boxconstinput=document.querySelector('#searchBox');input?.addEventListener('input',(event:Event)=>{consttarget=event.targetasHTMLInputElement;debouncedSearch(target.value);});
Enter fullscreen modeExit fullscreen mode

In this example:

  • handleSearch is the function that handles the search logic.
  • debouncedSearch ensures thathandleSearch is executed only after 300 milliseconds of inactivity in typing.

Parameters

  1. fn (Function): The function to be executed after the debounce delay.

    • This is the callback function that will be invoked after the specified delay.
  2. delay (Number, optional): The number of milliseconds to wait before invokingfn. Defaults to 400 milliseconds.

    • This determines the debounce interval.

Returns

Thedboun function returns a new debounced version offn. The returned function delays the invocation offn until afterdelay milliseconds have passed since the last time the returned function was called.

How It Works

  • When the returned function is called, it clears any existing timer set for the function (clearTimeout(timeout)).
  • A new timer is then set (setTimeout) to invokefn after the specifieddelay.
  • If the returned function is called again before the delay period ends, the previous timer is cleared and reset.

Practical Applications

  1. Input Handling: Debouncing prevents excessive execution of event handlers when users type in an input field.
  2. Resize Events: Manage performance by debouncing window resize event handlers.
  3. Scroll Events: Avoid performance bottlenecks by controlling how often scroll event handlers are executed.

Notes

  • If you need immediate execution followed by a delay (throttle-like behavior), this function does not provide that functionality out of the box.
  • Always ensuredelay is appropriate for the use case to balance responsiveness and performance.

Browser Compatibility

Thedboun function uses modern JavaScript/TypeScript features, making it compatible with most modern environments. For older environments, consider transpiling the code.

Testing

// Test debounced functionconstlog=dboun((message:string)=>console.log(message),500);log("Hello");// Will not log immediatelylog("Hello again");// Resets the timer; only this message will log after 500ms
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

🌐 Full-stack web developer | 🌟 Open-source enthusiast | 🚀 Innovator
  • Pronouns
    he/him
  • Work
    Head of IT at PIE International Education
  • Joined

More fromNaxrul Ahmed

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp