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);
}
}
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)
}
}
}
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>
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❤
Top comments (0)