Debounce - Leetcode 2627 - JavaScript 30-Day Challenge
Key Takeaways
The video demonstrates how to implement a debounced function in JavaScript, using the Leetcode 2627 problem as an example, and discusses the concept of debouncing and its applications.
Full Transcript
hey everyone welcome back and let's write some more neat code today today let's solve the problem to bounce this is actually a pretty practical problem and thankfully it's not super complicated to code up so I really want to focus on the actual conceptual part which is probably going to be the most important for you in your career debouncing is about delaying some execution and sometimes it's just about preventing some operation from happening multiple times in some time span in this case that is going to be provided for us but let's first understand what this problem is asking for once we know that I'll tell you some applications of this and then we'll solve the problem so this is the example code down here we have the function we're passing in which is console.log we're not calling it that's just what we're passing in and we are decorating it with the bounce and passing in 100 milliseconds as the time threshold so then our log function is here we can call it just like a normal log function now just looking at this line over here can be misleading because if we only called this line and we didn't have the stuff below it this would actually execute and it would execute after a hundred milliseconds because that was the delay that was passed in here so this should execute after 100 milliseconds but if we have another line of code right after it this stuff isn't really a synchronous this second line is going to execute immediately after this one up here that's why this one gets canceled calling this won't cancel it the next line cancels the previous line because this probably is going to execute before 100 milliseconds have passed and what we want consecutive calls to this function to do are cancel the previous calls if a hundred milliseconds haven't passed yet and in this case it hasn't so this one would cancel this guy and then the third one would cancel the previous one and this one doesn't have any calls after it so this one will be the one that actually executes but it's not going to execute immediately it will only happen after 100 milliseconds and when I say execute Q I mean the text will actually be logged because we know yes this function is executing but the inner implementation will be delayed by a hundred millisecond now suppose we call this at time equals zero milliseconds and we called the second one over here at time equals 200 milliseconds that would have given this guy plenty of time to execute after 100 milliseconds at time equals 100 milliseconds it would execute and then later this one would have executed and if you want to see like an actual representation of that this is kind of how we could do that we could delay the second one first we would create an anonymous function which would call this part and then we would delay it by let's say 200 milliseconds and in that case both of these would be logged now why would you ever want to do this well it's actually really common for example if we're making some type of search query maybe on Google and as we type things in we want it to auto complete but probably to auto complete or to give us like a list of suggestions it might have to make some kind of API call and every single time we type in a character like if I type in n e the auto completion will change but if I'm typing really fast we probably don't want to have to make 20 API calls if I typed 20 characters so we might delay it by 100 seconds so that I type 10 characters or let's say eight characters I type neat code and then I stop for maybe 100 milliseconds then it finally makes an API call to list to me the suggestions maybe the first one is neat code IO or something like that so not only does it delay the execution but it cancels the previous executions it won't make eight API calls it'll cancel the first seven it'll only execute the eighth one now another use case I'm going to open up my Dev tools inspect I'm going to show you the network tab every time we press the submit button here you can see an API call gets made to leak code submit API it takes in the code that we wrote here as the typed code parameter and usually when you press submit the UI changes immediately to prevent you from clicking it again but what if somehow you were able to double click that it would make multiple API calls in this case it doesn't really matter but you can imagine in some cases like if we're making payments you definitely don't want to double charge someone that's like the biggest problem when it comes to payments double charging and it actually still happens in the real world sometimes and in some cases The Bouncing can be implemented in the UI to prevent this but to be honest the best solution for this would be to add some type of item potency key because we would want it so that if we made the same API call multiple times only one of them executes okay we're probably getting a little bit too far away from the problem at this point now let's actually get into the problem thankfully it's not super complicated I'm going to comment this out so as you can imagine we want to call this function after this many seconds well the best way to do that would be set timeout we want to pass in these args and remember set time out the first parameter it takes is a function in this case I'm going to create an inline function and say FN passing in the args that are provided we want this to execute after T milliseconds a naive way to write this would have just been to do this but this is not a function this is a function call we don't actually want to call the function yet we want to pass in a function so we have to add kind of a wrapper around it so that the args can actually be passed in when we want to execute it okay that's simple enough we've added the delay but what if subsequent calls happen what if now this function is called again how do we cancel the previous one and how do we even know if we should cancel the previous one well to cancel a set timeout we need to store the ID and I could declare a variable here but we know we're going to need this on the next execution so I'm actually going to save this in a variable up here which I'm going to call ID which is initially going to be undefined and with this ID then we can actually cancel the timeout with clear timeout but the question is when do we want to execute this where do we want to execute it well in theory we would only want to call this if the previous this function call had not executed yet meaning this much time had not passed yet and we'd want to do that before we call the new set timeout so this is how we would want to do it but the way this is coded it's always going to clear the previous timeout what if the previous function had already been finished executing what would this do would it cause any problems can we cancel a set timeout that's already been completed no we can't even if ID is some real number like one or whatever and the function had already finished this canceled this clear would not do anything so it's not hurting us to put it there okay well what if we call this on the first execution of the function when ID is undefined when we're passing in undefined well if you're scared of that you could make a check here and we could even do that with I think the nullish coalescing operator if this is undefined we would probably not want to execute this so maybe an if statement would be better but the good thing is we can actually pass in undefined into this I didn't know about that I learned that today as well so I guess you learned something new every day but now let's run this to make sure that it works and as you can see yes it does don't let the runtime fool you this is a pretty efficient solution if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatco.io thanks for watching and I'll see you soon
Original Description
Solving Day 15 of the Leetcode 30-day javascript challenge. Today implement a debounced function and learn about some of the applications of debouncing.
🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews
🥷 Discord: https://discord.gg/ddjKRXPqtk
🐦 Twitter: https://twitter.com/neetcode1
🐮 Support the channel: https://www.patreon.com/NEETcode
⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf
💡 DYNAMIC PROGRAMMING PLAYLIST: https://www.youtube.com/watch?v=73r3KWiEvyk&list=PLot-Xpze53lcvx_tjrr_m2lgD2NsRHlNO&index=1
Problem Link: https://leetcode.com/problems/debounce/
0:00 - Read the problem
0:35 - Read example
2:40 - Use case: Search suggestions
3:35 - Use case: Form submission
4:35 - Coding Solution
leetcode 2627
#neetcode #leetcode #python
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeetCodeIO · NeetCodeIO · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
Design Linked List - Leetcode 707 - Python
NeetCodeIO
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
LFU Cache - Leetcode 460 - Python
NeetCodeIO
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
IPO - Leetcode 502 - Python
NeetCodeIO
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
Sort an Array - Leetcode 912 - Python
NeetCodeIO
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO
More on: Systems Design Basics
View skill →Related Reads
📰
📰
📰
📰
O(N) Manacher's Algorithm with Mirror Boundary Optimization
Dev.to · Dipaditya Das
Building a Power Grid Inside Minecraft with BFS Algorithms
Dev.to · Carlos Cortez 🇵🇪 [AWS Hero]
The Run-Length Encoding Trick: How Simple Strings Get Compressed
Medium · Programming
75 Days of Leetcode — Day 4: #238 — Product of Array Except Self
Medium · AI
Chapters (5)
Read the problem
0:35
Read example
2:40
Use case: Search suggestions
3:35
Use case: Form submission
4:35
Coding Solution
🎓
Tutor Explanation
DeepCamp AI