Throttling in Javascript | Walmart Frontend Interview Question

Throttling in Javascript | Walmart Frontend Interview Question

Akshay Saini

5 лет назад

166,472 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

@Pepcoding
@Pepcoding - 31.07.2022 20:58

throttle function mei se let flag = true ko bahar nikale bina throttle nahi karega. har returned function ne alag flag pe closure bna lia hai. sab returned functions ko same flag pe closure bnana hoga isko sahi chalne ke liye.

Ответить
@sarangtamrakar8723
@sarangtamrakar8723 - 13.08.2022 21:00

function throatling(fn,d){
let timer = new Date().getTime();

return function(){

if((new Date().getTime()-timer)>d){
fn();
timer = new Date().getTime();
}
}
}

betterfunction = throatling(getData,2000);


document.getElementById("fname").addEventListener("keyup", betterfunction);

Ответить
@nitishgupta8393
@nitishgupta8393 - 17.08.2022 05:17

I have just watched a genius, you are gem man

Ответить
@srikanthkolisetty5921
@srikanthkolisetty5921 - 11.09.2022 06:22

Thank you akshay

Ответить
@harshtiwari6933
@harshtiwari6933 - 19.09.2022 14:56

I do not get that every time the function is called, flag will be reset .. so how does changing flag value have any impact at all..

Ответить
@vishwajeetgade1325
@vishwajeetgade1325 - 11.10.2022 11:19

can you explain how you closure variable is working because throttle function is getting called multiple time on resize and then flag will be true on each throttle then expensive function will be called on each flag true what was the purpose of setTimeout it only set flag to true which is already true on each throttle function call

Ответить
@susmitobhattacharyya1668
@susmitobhattacharyya1668 - 25.10.2022 11:51

What a content. But have a doubt that don't we need to clear the timeouts like we did in the debouncing?

Ответить
@prikshit8
@prikshit8 - 25.11.2022 21:24

Amazing 🤩

Ответить
@159binny
@159binny - 02.12.2022 11:57

These days interviewers are using the examples even given by you. One person asked me how do you limit Clicks in a game and the same story you described. What a revolution you have brought.

Ответить
@01binaryboy
@01binaryboy - 05.12.2022 08:11

Thanks!

Ответить
@roviaasucksateverything501
@roviaasucksateverything501 - 12.12.2022 09:44

Where are the arguments coming from in throttle function @Akshay Saini

Ответить
@OveekChatterjee
@OveekChatterjee - 15.01.2023 07:35

Hi Akshay, First of all thank you soo much for such wonderful explaination of all these Js concepts

Just one quick query, what would be the corner case where the context and args will be used and how will they work. I know about the Apply method but how till linking the"this" and "arguments" will help in this case is not clear to me

thank you in advance!

Ответить
@SSK-KiNGz
@SSK-KiNGz - 21.02.2023 17:11

explanation is clear but the throttle doesn't work, some letters go missing at the end unless the user gives another input.

Ответить
@danielbentum136
@danielbentum136 - 13.03.2023 13:06

Thumbs up Akshay. with your little diagram |||||||||||||||||||||....... 'Flag = true' "Fn - effective" 'Flag = false'------"Fn - Not effective" ------ " wait for TimeOut Limit"--------- 'Flag = True' -----♻♻.
I hope im right

Ответить
@ashishprasad2949
@ashishprasad2949 - 17.03.2023 18:52

After i had watched code for debouncing and saw diff b/w debouncing and throttling, my first idea was tht one must use setInterval in case of throttling....alas, how wrong i was....

Ответить
@sanjay9970
@sanjay9970 - 21.04.2023 17:49

why are you using let context = this? what is the purpose of using that?

Ответить
@yeswanthh5068
@yeswanthh5068 - 16.05.2023 08:04

I really miss the old akhsay😥😓

Ответить
@itsMohak
@itsMohak - 30.05.2023 08:25

You are terrific.

Ответить
@Aman-Verma
@Aman-Verma - 06.06.2023 15:27

Hi Akshay, very nicely explained. But there is one edge case that you missed. Could you explain a way to solve that.
Edge case:-
Suppose the delay is 1 sec. But if the user ends up typing within 1 sec. then I think this would cause issue, as the function would not be executed (even though the flag would be true but, to execute the function user needs to enter something but in this case he already entered before 1 sec i.e before setTimeout sets the flag to true)

Ответить
@lokeshlokesh-fx8le
@lokeshlokesh-fx8le - 05.07.2023 10:05

In throttling, This flag method is easily understandable when compared to cleartimeout(timer) method.

Ответить
@Shahrukh-p2z
@Shahrukh-p2z - 06.07.2023 22:19

Thank you so much for sharing your knowledge i learned so much from you no one taught me this even in my company

Ответить
@jsagar95
@jsagar95 - 08.07.2023 20:22

Thanks!

Ответить
@nileshkokare2121
@nileshkokare2121 - 30.07.2023 13:48

Understood!

Ответить
@kikish_sabina
@kikish_sabina - 22.08.2023 21:04

Very clear explanation 👍🏻👍🏻👍🏻 thank you!

Ответить
@prashanthitssn1268
@prashanthitssn1268 - 30.08.2023 19:19

PLease use a mic :(

Ответить
@ikik790
@ikik790 - 13.11.2023 17:50

completed

Ответить
@Atavija
@Atavija - 17.11.2023 10:24

Akshay very good Thanks !!!

Ответить
@DevaKumar-jr5dh
@DevaKumar-jr5dh - 24.11.2023 21:18

the returned function should take parameter in form of rest operator I think you missed that

Ответить
@coolme7437
@coolme7437 - 12.12.2023 00:49

let counter = 0;
const getData = (args) => {
console.log("Getting the data...", ++counter, " ", args);
};
const throttle = function (fn, delay) {
let flag = true;
return function (...args) {
if (flag) {
fn.apply(this, args);
flag = false;
setTimeout(() => {
flag = true;
}, delay);
}
};
};
const debounceApi = throttle(getData, 300);

Ответить
@pradeexsu
@pradeexsu - 17.01.2024 14:41

this is nice one, thanks, akshay what if we are hitting simultaneously sufficient number of request, does we need a lock mechanism, or is flag enough?

Ответить
@RavindraSingh-zg9eq
@RavindraSingh-zg9eq - 21.01.2024 21:18

what an explaination bhai amazing superb ,i have seen this code but i was asking myself why they r writing this line of code but u explained very clearly ,mostly i was having doubt with args but u explained veryy nice

Ответить
@rohitkadam9150
@rohitkadam9150 - 30.01.2024 09:22

Hi @akshay bhai...
Just a doubt ...
Cant we achive this same thing , by disbaling the button for 1 sec call the function and after a sec enable the button to , stop calling the function again n again?

Open to hear everyones suggestions...

Ответить
@akashdutta1620
@akashdutta1620 - 14.02.2024 12:46

Me watching this video while clicking the subscribe/unsubcribe button repeatedly....
The subscribe button on the right side, there is no throttling..

Ответить
@kushagraagrawal7690
@kushagraagrawal7690 - 11.03.2024 20:53

Glad i achieved the same functionality using date.now(). Thanks for making js so amazing

Ответить
@SujitGawand0001
@SujitGawand0001 - 17.03.2024 10:27

I wish you use vs code and desktop to demo this explanation, by using whiteboard it is more difficult to understand.
Video of debouncing much better due to usage of monitor.

Ответить
@Mr.Zeus11
@Mr.Zeus11 - 31.03.2024 21:25

/* throttling function */

let throttlingTime = null;
let throttling = function (fun, time) {
if (throttlingTime) return;
throttlingTime = setInterval(() => {
fun();
clearInterval(throttlingTime);
throttlingTime = null;
}, time)
}

window.addEventListener('resize', () => {
throttling(callThrottlingFun, 1000)
})

let callThrottlingFun = (width) => {
console.log(window.innerWidth)
}

Ответить
@JonnyWarker-y7d
@JonnyWarker-y7d - 05.05.2024 14:18

I think there is a bug in your code

Ответить
@AdnanAli-cp9hk
@AdnanAli-cp9hk - 20.05.2024 13:07

Awesome explanation Sir, thank you so much.

Ответить
@santoshbiradar4650
@santoshbiradar4650 - 25.05.2024 07:01

We can use sttimeInterval instead of SetTimeOut and flag right ?

Ответить
@rushivani454
@rushivani454 - 04.06.2024 20:30

Please do it in pc also after explaining it in board. So that we can see how it works and code is error free

Ответить
@shravansaini9922
@shravansaini9922 - 21.07.2024 17:46

if(flag){
flag = false;
func()
}

Ответить
@akakiburjanadze
@akakiburjanadze - 23.07.2024 20:31

Dude your videos are simply amaizing! I have learned 10x more than that what I knew before and feel so much confident in my JavaScript knowledge. Big Thanks!

Ответить
@malikazharabbas5898
@malikazharabbas5898 - 19.08.2024 13:53

Debouncing: Stop the execution until the period of inactivity.
Throttling: Limit the execution to a fixed number of times over an interval

but in your given example where we are passing the number of limit in this we are only delaying the function not limiting.

I am confusing in Debouncing and Throttling example anyone explain me .

here is my code for Debouncing

const handleSearch = (e) => {
console.log("value: ", e.target.value);
};

const debounce = (fn, delay) => {
let timeoutId;
return (e) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fn(e);
}, delay);
};
};

let betterDebounce = debounce(handleSearch, 300);

// Add an event listener to an input field
const inputField = document.getElementById("search-input");
inputField.addEventListener("input", betterDebounce);


this for Throttling:
const runResizeLog = () => {
console.log("resize-log");
};

const throttle = (fn, limit) => {
let flag = true;
return () => {
if (flag) {
fn();
flag = false;
setTimeout(() => {
flag = true;
}, limit);
}
};
};

let betterThrottle = throttle(runResizeLog, 500);

window.addEventListener("resize", betterThrottle);

Ответить
@tanmay496
@tanmay496 - 11.09.2024 20:22

---------------------
HTML Code
-----------------
<button onclick="callGetDataWisely()">
click me
</button>
-------------------
JS Code
------------------
let counter = 0;
function getData(){
console.log("Calling very expensive api ..." + counter++)
}

function throttling(cb, d){
let timer;
let allowClick = true;
return function(){
if(allowClick){
cb();
allowClick = false;
}
else{
clearInterval(timer);
timer = setTimeout(()=>{
cb();
allowClick = true;
},d)
}

}

}

let callGetDataWisely = throttling(getData,1000)

Ответить
@tanmay496
@tanmay496 - 11.09.2024 20:24

Thanks it's now clear

Ответить
@tejasparmar462
@tejasparmar462 - 22.09.2024 15:33

I can see on codepen site only around 9000 people watched code. I can see 1.5 lakh views in this video but only a few checked code.
people only listen and do not understand the code after some days forget concept

Ответить
@deepanshjohri3997
@deepanshjohri3997 - 20.01.2025 13:42

Working Code :

// Higher Order Function
const throttle = function (func,delay) {
let flag = true;
let context = this;
console.log(context);

return function call(...args) {
console.log("under throttle call");
if (flag) {
func.apply(this,args);
flag = false;
setTimeout(() => flag = true, delay);
}
}
}

const throttledFunction = throttle(expensiveFn,500);

document.getElementById("btn").addEventListener("click", throttledFunction);

function expensiveFn() {
console.log("expensive function this : "+this);
}

Ответить
@medamsaisirisha847
@medamsaisirisha847 - 28.04.2020 15:11

Had faced an interview question almost a year back to limit the network calls to API, now after watching your videos finally got the answer which I have been searching for, thanks to linkedin which brought me here to your channel. Explained it really well sir.

Ответить