Learn Debounce And Throttle In 16 Minutes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
debouncing and throttling are great ways to not only improve your user experience but also save yourself quite a bit of money in this video i'm going to show you how to use debounce and throttling in javascript as well as comparing the differences between them [Music] welcome back to web dev simplified my name is kyle and my job is to simplify the web for you so you can start building your dream project sooner in today's video i'm going to be talking about throttle and debounce and why they're important to understand to get started i have a basic index html file which just has a text input as you can see on the right-hand side here it has a default tab which we can put some text inside of a d-mount section which some text we can add and a throttle section where we can add some text just so we can compare the differences between the default behavior debounce behavior and throttle behavior i also have all of those elements selected so we can actually work with them the first thing i want to talk about is how we can actually see the differences between d bounce throttle and why they're important let's take our input element and i want to add an event listener for whenever our input changes so anytime that we type anything into our input this event listener is going to run and all i want to do is i want to take our default text and i'm going to set the text to the value of our input so what this is going to do is every time i type something you can see it shows up in this default section down here now when you're just working locally on your computer this works fine i mean this is super quick it's not going to cause any performance problems it doesn't matter what your network connection is and that's just because we're just storing everything locally in our page what happens if let's say this is like an auto complete box and i start typing something and what it does is actually goes to the server and queries a bunch of information to say hey give me everything that you know has said in the name for example and then it brings you back a list so imagine you're like querying a movie database and you want to find all the movies with the name matrix in them well what it's going to do is as you type each character it's going to send a brand new request because this event gets fired every single time you type a character so when i type m it's going to make a request for all the movies that start with m then when i hit a it's now going to look for all the movies that have m a in them and then t and r and i and x and just by typing out the word matrix we made six requests to our server which are all going to come back at different rates and that is not only going to cause some ui problems but also that's a huge burden for the people using your code because now they just made six network requests downloaded them and if they're on a slow connection or using data that's going to burn through their data and it's going to really slow down the app if their connection is not quick enough to keep up this is where debouncing and throttling come in really useful they are there as a way to actually slow down a function instead of calling a function every single time what it's going to do is it's only going to call that function after a set delay and that delay is going to be different based on debouncing and throttling they have a different way of working so the way that d bounce works is instead of running the function every single time that you do something in our case every time we type a character it's going to run the function instead what happens is it says hey has there been a delay since the last time you tried to call this function so when i type s it's going to call the function but it's going to wait it's going to wait let's say one second and as long as nothing changes in that one second then the function will run but if during that one second i type another character well it's going to say okay something has changed reset our timer back to one second and wait to see if anything has changed if i type another character in that one second it resets again essentially debounce waits until there's been at least a set period of time in our case one second before it actually calls the function so let's look at implementing a debounce version of this we'll come in here we'll create a function called debounce and the way this debounce function is going to work is i'm going to pass it a callback function i'm going to pass it a delay and our just delay is going to be defaulted to one second and inside here what we want to do is we want to call this callback function after the delay as long as we haven't recalled our debounce in the past and the way this debounce function works is we give it a function inside of it so what we can do is we can say like update the bounce text is going to be the function we create we're going to call deep bounce we're going to pass it in a callback and this callback is going to take in the text you want to update and it's just going to take our debounce text and it's going to update it so just like this all we're doing is we're just updating the text for our d bounce text and that's what we're passing as our callback to this function now inside of here we need to do the logic to make sure that this callback is only called a limited amount of times so first of all we need to return it as a function because the way we're going to call this is we'll say update debounce text we're going to pass in that text just like that so now this d bounce needs to return to us a function and this function is going to take in any amount of arguments it doesn't matter we want to make sure it's generic because if we have a callback that takes in 10 arguments one argument zero arguments it doesn't matter this is going to get all of the arguments and inside of here we want to set up that timer so we're going to choose a set timeout for that and the set timeout is just going to inside of it call our callback with our arguments we're going to spread those out and we're going to make sure we to wait for our delay so by default what this does is it's just forcing our function to wait one second before it actually runs so if we save this and we just hit a here you can see after one second the text and d bounds changes to a if i change the text here you can see after one second each element is going to be putting itself in there but that's not how d balance works that's just delaying things by a second we want to make sure all of those calls for the a the s the d they actually don't run until we're done typing everything completely so the way we do that is we just save a variable here for our timeout so we'll set it to nothing by default and then here we're going to say timeout is equal to this and what i want to do is i just want to clear that timeout every time i call this function so now what's happening is when i call debounce here i'm running this function i'm creating this timeout variable and i'm returning a new function and inside this function i'm just clearing out our current timeout and creating a new one so every time that my input changes i call this update function and this update function clears my original timeout and starts a new one second timer so as long as there's less than one second delay between calling this function it'll never do anything it waits until there's at least a one second delay before it actually runs let's take a look at that if i type in something and i make sure that there's never a second delay i always type things quick enough now if i wait a second you can see that that function runs and it ran just one time it updated all the input at once same thing if i just start deleting things as long as i don't have more than a second delay it's going to wait until there's a delay and then it's going to call that function this is really important because again if you're fetching from an api you don't want to fetch every single time they type a character like we're doing in this default here we want to wait until they're done typing and then we make that fetch so you might make this delay shorter you know for example we could change the delay here to like 250 milliseconds now as long as there's a 250 millisecond delay it's going to make that api request and it's not going to really be noticeable to the user but it'll drastically increase the speed for them because they're not having to make 10 requests if you type 10 characters and it's going to save you a lot of money because you won't have 10 requests hitting your server so debouncing is really useful in these scenarios where you have auto complete that you need to do where like people are typing in things essentially debounce is great when you want to make sure you do one request after everything is changed like if you have a bunch of changes happening all at once you can kind of batch them up and send them all off at once with the d-bounce throttle on the other hand is a little bit different than d-bounds throttle works where it delays your function call but instead of waiting until everything is done what throttle does is it says okay as soon as you make a change i'm going to send off a request and then every single second if that's your delay i'm going to continually send a new request based on whatever the last input was so in the throttle example let's say i type s it's going to send a request and then let's say i type fds a or e and then after that it's been one second now it's going to send this and if i just continue typing after one second it's going to send whatever the new value is and again after one second it sends the new value until there are no more changes this is great where things are changing a lot and you want to be able to just make sure you send the most recent request so for example if you're resizing a window or you're doing scrolling it's really useful to do throttling in that case because you don't really want to wait until they're done resizing or done scrolling you want to figure out where they are as you're going but you don't want to call that method a hundred thousand times because scrolling and resizing they make a lot of event calls so by using throttle you can limit the amount of power that the cpu needs to use in order to execute all of them because you're slowing them down it's a little bit complicated but let me show you exactly how it works and it'll be much easier to understand so we're going to create another function called throttle and it's going to work exactly the same we take a callback and a delay which by default we're going to set to a thousand and we'll get rid of that 250 millisecond delay up here so we can really compare these now we need to call that throttle function by saying we'll say this is update throttle text and we're going to call throttle and it's going to take in that text and we're going to change this to our throttle text and we're just going to call that function down here with our target value so now all we need to do is actually implement our throttle and there's two main ways to implement it i'll show you the easier way and then the more complex way second so with a throttle the main thing that's different from d-bounce is d-bounce waits until there's been a second delay before it runs and with throttle it runs immediately when you call the function so let's return our function which has our arguments just like we did with our d-bounds and what we want to do inside of here is we want to immediately call the function as soon as we execute it so we're going to call our callback with our arguments that's the very first thing we're going to do and then what we want to do is we want to say hey you know what now we need to wait one second or whatever our delay is until we call this function again so we're going to create a set timeout and this set timeout is just going to be set to that delay which in our case is one second by default and inside of here we're going to set a variable this variable is called should wait and call whatever we want and we're going to set that to false and what this variable does is say hey if we're within this waiting period this variable will be true which means don't call the function so in our case what we're going to do here is we're going to say if should wait then we just return so by default should weight is false so this is not going to return it's going to call our callback function then we want to set should weight to true so we'll set it to true here and then we want to wait one second or whatever our delay is and after that we set our should weight equal to false the way that this works is the first time we call throttle it immediately calls our callback function and then every other time that we call it it does nothing until our delay has finished once our delay has finished this should weight gets set back to false which means it no longer returns here it calls the function again forces you to wait and you have to wait another second so let's see how throttle works here if i type in s you see immediately throttle gets that input of s right away while the d-bounce takes a second but if i start typing in a bunch of characters you can see the throttle is getting it and every second it's updating that value but you'll notice something a little bit interesting about throttle if i just type in like asdf you can see throttle gets just the a but it's not getting the s d and f portion and that's because we didn't have another event happen after one second all of these events happened within one second so the very first event got ran with this callback but none of the other events got ran afterwards so we need to actually tweak our throttle method a little bit to make it more advanced so that it'll save whatever the last call to it was and send that out after that one second that way you make sure you get this other information into it so in order to handle that we need to add a new variable we'll call this waiting args and this waiting args is going to be the argument for the function that we call when we're actually waiting so if should weight is true what we need to do in here is take our weighting arguments and set it equal to those args and then we return so now what we're doing is every time we are in the waiting stage we're saving whatever the last call to the function was we're saving those arguments so we can call the function later with those arguments then this part is fine right here the next part with our set timeout needs to change though because what if we have waiting arguments that we need to take care of so what we can do here is we can take our weighting arguments if it's equal to null that means that we don't have anything waiting to happen so we can just treat this exactly like it was before we can set our should weight equal to false and then it'll wait until the next response before anything happens this is great if you have like one event that happens and then three seconds later a new event this is going to work just fine then what happens though if we make two calls so for example we come back in here and i type in a s you would notice it prints out the a but it doesn't print the s out and that's because we made two calls the first one came in nothing happened the second one came in we're saving that to our waiting arguments so we need to do is if we have waiting arguments i want to call our function after that second with those waiting arguments so we'll spread those out just like this then what i want to do is set our weighting arguments equal to null so that way we don't save that information anymore and then i want to just restart our timer because we already called it we need to restart our one second timer so i'm going to take this function right here i'm just going to put this into its own variable we're just going to call it timeout func just like that and then what i can do is just call set timeout inside of here asset our timeout func and our delay and what i can do down here is the same thing so in order to explain exactly what's going on here is we're saving the last call that we made after we made a call so we called the throttle it ran just fine when we call it once nothing changes it works just like a normal call if we call it a second time during this waiting period it saves that call and it says hey you know what you called this function i'm going to execute this as soon as the delay is over so that way you don't send more than one call per second in our case so it's waiting it's waiting is waiting it's finally done waiting it's saying hey we have some waiting arguments follow with those waiting arguments and start your wait over again for the next one so now with that done we just type in asd you'll see that it's going to work we'll just do it a little bit different here i'll type in really quickly asdf and you can see i guess that's a little too quick we'll wait for this wait a full second asdf or as you can see it prints out the a that worked fine and then after a second delay it printed out the s as well it's making sure to catch that last call and always send it every time that's really important to make sure you do with throttle now this example that we're covering right here really isn't that useful for throttling because this is something you'd want to handle with d-bounds but i mentioned a few use cases like resizing but another one is mouse movement if you want to track the mouse movement that function gets called all the time so you may want to throttle that so it doesn't call it quite as often so let's set up a really simple event we're just going to say document add event listener and this event listener here is just going to be for mouse move so every time we move our mouse this event is going to get called and all i want to do in here is i want to increment a number between 0 and whatever for how many times this function has been called so all i want to do is i'm going to scroll down here i'm going to paste this function it's called increment count we pass it an element and all it's going to do is increment the count for that function and it's going to tell us how many times default has been called d bounce has been called and throttle has been called so we can just say here increment count of our default text and now as you can see as i move my mouse you can see just by moving my mouse a little bit we've already called this function 354 times that is insane that depending on how much code you have inside this function it could really slow down especially slower devices so let's look at what happens when we do debouncing and throttling what i'm going to do is i'm going to just copy this scroll up here to where we implement these update functions i'm going to replace the implementation for these functions so here we're going to increment our debounce text and here i'm going to increment our throttle text just like that and this entire section with the input we don't need that anymore we can just get rid of that so now when we update our throttle and debounce text we're actually just incrementing those values so we can call update d-bounds text and update throttle text just like that and now if i come over here and move my mouse you can see throttle is getting called once every single second our default is getting called obviously every time we move our mouse and debounce it's waiting until there's been an entire second between when i move my mouse and the next time i move it so if i pause and don't move my mouse now you can see d bounce gets called once and obviously in our case you'd probably want to increase the frequency of our throttle so maybe make it like every 10 milliseconds and then when we move actually maybe like every 100 milliseconds would be fine there we go so now when i move you can see that this is only being called 10 times a second which for most use cases is probably fine instead of being called you know 796 times it's only being called 58. so with throttling you can do things like mouse movement for drag and drop you can do things like resizing scrolling those are really good use cases for throttling where you want to make sure you're sending out requests but you don't want to send them out too quickly because it could slow down devices slow down your api and so on now if you enjoyed this video and want to see how to implement debouncing in react i have a full video on that it's going to be linked over here and if you want to see a project that's the perfect use case for deep bouncing i have a search bar project also linked over here in javascript with that said thank you very much for watching and have a good day
Info
Channel: Web Dev Simplified
Views: 114,712
Rating: undefined out of 5
Keywords: webdevsimplified, debounce, throttle, javascript, js, js debounce, js throttle, javascript debounce, javascript throttle, debounce vs throttle, debounce vs throttle js, debounce vs throttle javascript
Id: cjIswDCKgu0
Channel Id: undefined
Length: 16min 28sec (988 seconds)
Published: Sat Apr 02 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.