Interview10: DeBounce, Throttle, and Polyfill for Flat in JavaScript
Deep Dive into DeBounce and Throttle in JavaScript
In this article, we are talking about DeBounce, Throttle, Flat and how to implement the DeBounce and Throttle in Javascript.
What is DeBounce?
Debouncing is a way of delaying the execution of a function until a certain amount of time has passed since the last time it was called.
1. DeBounce in JavaScript
function deBounce (func, delay) {
let timeoutId;
return function(...arg) {
clearTimeout(timer);
timeoutId = setTimeout(() => func.apply(this, args), delay)
}
}
var delayCb = deBounce(func, 500);What is Throttle?
Throttling is a technique that is used to throttle or ignore the continuous occurrence of a particular event or task for a particular interval of time and execute the code again after that specified time if the event or the task continues occurring
2. Throttle in JavaScript
function throttle (fn, delay) {
isDelay = false;
return function(...args) {
if(!isDelay) {
fn.apply(this, args);
isDelay = true;
setTimeout(function(){
isDelay = false;
}, delay)
}
}
}What is Flat?
The flat() method in JavaScript creates a new array with all sub-array elements concatenated into it recursively up to the specified depth
3. Polyfill for Flat in JavaScript
Array.prototype.flatPolyfill = function(depth = 1){
var arr = this;
var newArr = [];
function cb(arr, count) {
for(var i = 0; i < arr.length; i++) {
if(Object.prototype.toString.call(arr[i]) === '[object Array]' && count !== 0)
{
cb(arr[i], --count)
} else {
newArr.push(arr[i]);
}
}
}
cb(arr, depth);
return newArr;
}
[1, 2, [3, 4]].flatPolyfill(); // [1, 2, 3, 4]
[1, 2, [3, 4, [5, 6]]].flatPolyfill(); // [1, 2, 3, 4, [5, 6]]
[1, 2, [3, 4, [5, 6]]].flatPolyfill(2); // [1, 2, 3, 4, 5, 6]
[1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]].flatPolyfill(Infinity); // [1, 2, Thank you for reading until the end. Before you go, Please consider clapping and following.
Javascript is weird, I like the weird things. Keep Smiling.
Useful Links:
Interview-9: PolyFill for setInterval, clearInterval.
Get ✅ open src 🚀 🚀’s stories in your inbox
Join Medium for free to get updates from this writer.
Interview-10: You are reading, DeBounce, Throttle, and polyfill Flat in JS
Interview-11: Curry function in JavaScript
Stackademic 🎓
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us X | LinkedIn | YouTube | Discord
- Visit our other platforms: In Plain English | CoFeed | Differ
- More content at Stackademic.com











