DEV Community

Cover image for debouncing and throttling in javascript simplified by aryan
aryan015
aryan015

Posted on • Edited on

debouncing and throttling in javascript simplified by aryan

These jargon is nothing but ways to improve javascript❤ performance.

Debounce

Debounce is improved version of throttle. beware that it will only run when cursor stops running, might miss some important inputs. If you move the cursor within second then it will reset the cursor.
snippet.js

function debounce(fx,timer){
let id = null;
return function(...args){
    if(id){
  clearTimeout(id);
  }
  id = setTimeout(()=>{fx.apply(this,args);},timer);
}
}
Enter fullscreen mode Exit fullscreen mode

Throttle

Throttle is useful when you want to ensure that a function is called at a limited rate or frequency, without missing any important inputs or events.❤
snippet.js

// It will run
// after 1sec irrespective of cursor movement 
function throttle(fx,interval){
    let lastCall = 0;
    return function(...args){
        let now = Date.now();
        if(now-lastCall>=interval){
            lastCall = now;
            fx.apply(this,args)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
normal throttle debounce
1000 10 1

Do by yourself

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Counter</title>
    <!-- Add your CSS or external stylesheets here -->
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <!-- Your content goes here (always give parent element an unique id) -->
    <main id='main'>
    <!-- always try to give semantic elements I have avoided due to less style writes -->
    <section id='normal'>
    <span style="font-weigth:600;">Normal </span><span id='normal-counter'></span>
    </section>
    <section id='throttle'>
    <span style="font-weigth:600;">Throttle </span><span id='throttle-counter'><span>
    </section>
    <section id='debounce'>
    <span style="font-weigth:600;">Debounce </span><span id='debounce-counter'>12</span>
    </section>
    </main>
    <!-- Add your JavaScript or external scripts here -->
    <script src="script.js" defer></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

script.js

const tcounter = document.getElementById("throttle-counter");
const normal = document.getElementById("normal-counter");
const dcounter = document.getElementById("debounce-counter");

tcounter.innerText = '0'
dcounter.innerText = '0'
normal.innerText = '0'

window.addEventListener('mousemove',update)


// normal counter
let ncounter = 0;
// throttle counter
let tcount = 0;
// debounce counter
let dcount = 0;

// note: functions are hoisted
let isScroll = true;
function update(){
  // normal function
  normalUpdate();
  //throttle function
  // do not run before one second
  throttle(throttleUpdate,1000);
  // debounce function
  // run only after event stops
  debounce(dobounceUpdate,1000)
}
function normalUpdate(){
  console.log('normal')
  normal.innerText = ncounter++;
 }
function throttleUpdate(){
  tcounter.innerText = tcount++     
}
function debounceUpdate(){
        dcounter.innerText = dcount++;
}
// you can create a seperate module and import them to make codebase cleaner❤
Enter fullscreen mode Exit fullscreen mode

output
output

Validate html❤
video reference
my linkedin❤

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more