Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Debounce and Throttle Functions in JavaScript

Tech 1

Debounce Function

A debounce function delays the execution of a callback until after a specified waiting period has elapsed since the last time the function was invoked. This is useful for events that fire rapidly, such as window resizing or keyboard input, where you want to perform a action only after the user has stoped triggering the event.

function debounce(callback, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      callback.apply(this, args);
    }, delay);
  };
}

function handleInput() {
  console.log('Processing input...');
}

const inputElement = document.querySelector('input');
inputElement.addEventListener('input', debounce(handleInput, 300));

Throttle Functon

A throttle function ensures a callback is executed at most once per specified time interval. It's ideal for limiting the rate of execution during continuous events like scrolling or mouse movement.

function throttle(callback, interval) {
  let isThrottled = false;
  return function(...args) {
    if (isThrottled) return;
    isThrottled = true;
    setTimeout(() => {
      callback.apply(this, args);
      isThrottled = false;
    }, interval);
  };
}

function handleScroll() {
  console.log('Handling scroll event.');
}

window.addEventListener('scroll', throttle(handleScroll, 200));
Tags: javascript

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.