Transcript
00:00 Here you have a debounce utility function. It accepts callback as an argument and returns a debounce version of that callback. Debouncing is very handy because what it will do, it will wrap any function so that it only gets called when a particular duration has passed since its last
00:15 call. You probably use debounce in practice if you implemented something like a search field, where you can type something really fast, but you don't want to make a search request on every key stroke. Instead, you debounce that request until a certain amount of time passes since the last key stroke. This is precisely the utility to achieve that. It works internally by using the
00:35 setTimeout function and it delays the effect by a particular duration. Let me show you how you can try to test this function. So here I have an example test where I create a mock function called foo that accepts strings and then I debounce that function by wrapping it in debounce by 250
00:52 milliseconds. As a result, I get a bar which is a debounce version of foo. Then I call this bar function three times, supplying it different arguments, and what I expect to happen here is that when I call bar with one, it starts awaiting this idle interval, and then when I call it with two, it cancels this one because they happen immediately, so this window hasn't passed yet,
01:11 and then finally I call it with three and it cancels all the previous calls. So what I expect to happen from now, since nothing else is calling bar, foo, the originally debounced function, should be called once and it should be called with the argument three as a string. But if I try to
01:26 run this test, I will see it failing because foo hasn't been called at all. This is happening because there's actually a hidden race condition in this test. So this bar call, the last one, and this expect statement actually run at the same time. So expect statement fails first,
01:42 failing the test. In this exercise, your task will be to complete the existing test suite for the debounce function by mocking timers, because what you want to do effectively is somehow advance the time by this particular debounce window so you're able to assert on the debounce function reliably.