Debounce - Leetcode 2627 - JavaScript 30-Day Challenge

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·3y ago

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 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

The video teaches how to implement a debounced function in JavaScript, which delays the execution of a function and cancels previous executions if a certain time threshold has not been met. This concept is useful in real-world scenarios such as preventing multiple API calls or UI changes.

Key Takeaways
  1. Understand the concept of debouncing and its applications
  2. Implement a debounced function using setTimeout and clearTimeout
  3. Test the function to ensure it works as expected
  4. Apply debouncing to real-world scenarios such as API calls or UI changes
💡 Debouncing is a technique used to delay the execution of a function and cancel previous executions if a certain time threshold has not been met, which is useful in preventing multiple API calls or UI changes.

Related Reads

📰
O(N) Manacher's Algorithm with Mirror Boundary Optimization
Learn to optimize palindrome detection using Manacher's Algorithm with mirror boundary optimization, reducing time complexity to O(N)
Dev.to · Dipaditya Das
📰
Building a Power Grid Inside Minecraft with BFS Algorithms
Learn to build a power grid inside Minecraft using BFS algorithms and understand its relevance to cloud services
Dev.to · Carlos Cortez 🇵🇪 [AWS Hero]
📰
The Run-Length Encoding Trick: How Simple Strings Get Compressed
Learn how Run-Length Encoding (RLE) compresses simple strings, a fundamental technique in programming and data compression, and apply it to optimize storage and transmission of data
Medium · Programming
📰
75 Days of Leetcode — Day 4: #238 — Product of Array Except Self
Solve the Product of Array Except Self problem on LeetCode to improve coding skills and learn array manipulation techniques
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
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →