Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Debounce and Throttle Functions in JavaScript

Tech Apr 26 48

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...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

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