To understand the following explanations, imagine you are a 5-year-old who loves eating chocolates and have to ask your parents for it. Now let’s dive into how your mom and dad both handle this situation.
We all know that eating chocolate is very unhealthy for our bodies. That is why your mom has set a rule where she will give you the chocolate only if a day has passed since you had your last chocolate. To put in simple words, whenever you ask your mom for chocolate, there are two possibilities:
- If you have had chocolate in the last 24 hours, mom will ignore your request.
- Else, you will get a chocolate.
Now let us see how this fits in the programming world. If you call a throttled function, it will check if the desired amount of time has passed since the last execution. If yes, the function will be executed. Else it will return without executing.
The following image shows a timeline of calling a throttled function. The scale represents time in seconds. Imagine you are calling the throttle function each second and your throttle time is 5 seconds. So throttled function will be executed in 5 seconds intervals.
Your dad, on the other hand, wants to teach you the value of patience. He believes that you understand the value of something only if you have the patience to wait for it. To achieve this, your dad has set a rule where whenever you ask for chocolate, he will give you the chocolate after exactly one day. But, if you ask for chocolate within that hour, he will start time from 0 again. To put in simple words, whenever you ask your dad for chocolate, there are two possibilities:
- Your dad will set a timer for 24 hours and will give you the chocolate at the end of it.
- If you ask again while this timer is going on, your dad will start the timer from 0 again.
Similarly, if you call a debounced function in the programming world, your function will get executed in a certain amount of time. But if you call the function again within that time, the previous call is canceled and the function is executed after the desired time starting now.
The following diagram shows a timeline of debounced calls. Each number on the scale represents a second and your desired debounce time is 5 seconds.
I hope you are now clear on the topic of debounce vs throttle. If you want to learn more about how you can write your own debounce and throttle, you can refer to these posts
Until then, Happy Coding!!
This article was originally published here. For more such interesting reads, visit my blog.
Top comments (6)
You should write kids books!
Wow you explained this really well. Thanks
Thanks. I am glad you liked it
So debounce will call the function after 5seconds of our button click ?