Комментарии:
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.
Ответить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);
I have just watched a genius, you are gem man
ОтветитьThank you akshay
Ответить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..
Ответить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
ОтветитьWhat a content. But have a doubt that don't we need to clear the timeouts like we did in the debouncing?
ОтветитьAmazing 🤩
Ответить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.
ОтветитьThanks!
ОтветитьWhere are the arguments coming from in throttle function @Akshay Saini
Ответить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!
explanation is clear but the throttle doesn't work, some letters go missing at the end unless the user gives another input.
Ответить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
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....
Ответитьwhy are you using let context = this? what is the purpose of using that?
ОтветитьI really miss the old akhsay😥😓
ОтветитьYou are terrific.
Ответить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)
In throttling, This flag method is easily understandable when compared to cleartimeout(timer) method.
ОтветитьThank you so much for sharing your knowledge i learned so much from you no one taught me this even in my company
ОтветитьThanks!
ОтветитьUnderstood!
ОтветитьVery clear explanation 👍🏻👍🏻👍🏻 thank you!
ОтветитьPLease use a mic :(
Ответитьcompleted
ОтветитьAkshay very good Thanks !!!
Ответитьthe returned function should take parameter in form of rest operator I think you missed that
Ответить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);
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?
Ответить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
Ответить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...
Me watching this video while clicking the subscribe/unsubcribe button repeatedly....
The subscribe button on the right side, there is no throttling..
Glad i achieved the same functionality using date.now(). Thanks for making js so amazing
Ответить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.
/* 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)
}
I think there is a bug in your code
ОтветитьAwesome explanation Sir, thank you so much.
ОтветитьWe can use sttimeInterval instead of SetTimeOut and flag right ?
ОтветитьPlease do it in pc also after explaining it in board. So that we can see how it works and code is error free
Ответитьif(flag){
flag = false;
func()
}
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!
Ответить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);
---------------------
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)
Thanks it's now clear
Ответить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
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);
}
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.
Ответить