Last time we took on some key JS problems. These include:
- Getting an Array of names from an array of users.
- Getting an Array of names from an array of users where the user is active.
- Sort users based on age in descending order (highest to lowest)
- Create a counter function which has increment and getValue functionality (use closures)
- Write a function which implements a range from 1…50
This time we explore three new problems that include debouncing, throttling and implementing a shuffle function.
Let us start with the first problem. Debounce in Javascript.
1. Debounce in Javascript
A debounce function is a function that prevents multiple calls of a function in a specified period of time.
There are the following steps to implement a debounce function:
- Create a function that accepts another function and a timeout value.
- Now we need to implement a closure where we call the function with its arguments only after the completion of a timeout.
- We need to ensure that the previous timeout is not running when calling our function again and again. So we also use the clearTimeout function before we call our closure function.
E.g.
const debounce= ( fn, timeout=300)=>{
let timer;
return (...args)=>{
clearTimeout(timer);
timer=setTimeout(()=>{
fn.apply(this,args)
}, timeout)
}
}
const saveName =(name='')=>{
console.log("SavedName ", name)
}
const processName = debounce(saveName,2000);
processName('Ank');
processName('MAnk');
As seen above when we call the saveName function implemented through a debouncer, we ensure that multiple calls of the same aren’t fired in the given timeout value of 2000.
2. Throttle in Javascript
A throttle function is a function which will get executed immediately. Any other function calls after it only occurs after a certain period of time.
Much like a debouncer function in JS, the steps to implement a debounce function are quite similar.
Instead of clearing timeout, however, we first call the closure function and check whether, within a given timeframe, the closure function has been called/loaded and if so, we set a loaded flag to true. This flag only is set false once the timeout has fully ended.
const throttle = (fn, timeout = 300) => {
let hasLoaded = false;
return (...args) => {
if (!hasLoaded) {
fn.apply(this, args)
hasLoaded = true
setTimeout(() => {
hasloaded = false;
}, timeout)
}
}
}
const saveName = (name = '') => {
console.log("SavedName ", name)
}
const processName = throttle(saveName, 2000);
processName('Ank');
setTimeout(() => {
processName('mAnk');
}, 1000)
setTimeout(() => {
processName('TmAnk');
}, 1200)
setTimeout(() => {
processName('Ank');
}, 2400)
As seen above, once the processName function is called, for the next 2 seconds no other call will be executed. Only the last call shall be executed as it occurs after 2 seconds.
3. Shuffle function in Javascript
Unlike sorting, shuffling is the process of randomizing the elements placed in an array.
We shuffle in a four step process
1. We mutate our original array to contain a key for each item.
2. This numeric key can be generated using Math.random(). Now this will serve as an index we can use to shuffle items.
3. Next we sort the mutated array using this numeric key. Even though we are sorting the array, because of this random
numeric key, our elements will take completely random positions.
4. Finally, we get our original array back by doing a final mutation using map to get our object
const num =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
const shuffle =(items)=>{
return items.map((item)=>({sort:Math.random(),item})).sort((a,b)=>a.sort-b.sort).map((a)=>a.item)
}
console.log(shuffle(num))
So that is it for part 2! In part 3 we shall explore more such interesting applications of JS and how to implement a solution for them
Discover more in the next blog!!
I keep on coding something cool, visit ankush.tech to see what all I am doing!
If you wish to read about my work, here is a book that I published recently – “CSS Bullets, a comprehensive guide to all the CSS you need!“
Interested in React? Learn react from scratch with my book, “REACT Bullets“.
Thanks for sticking around!
Till next time, keep howling, hustling, and learning!

Leave a Reply