Mark As Completed Discussion

Good evening! Here's our prompt for today.

Both debouncing and throttling are intended to enhance a website's performance. They accomplish this primarily by limiting the number of times a function can execute.

In the case of throttling, the exact definition is that it's a technique where a function can be executed only once in any given time interval-- regardless of how many times the user fires the event.

When is this useful? Consider the example of infinite scroll. Each time the user scrolls to the bottom of the page, we'll want to execute a function to grab the next list of resources to display. However, it's really easy for a user to scroll back up a bit and then try again, possibly several times, if the results don't load fast enough. If we throttle that call, we won't make unnecessary, expensive network calls.

Please use the following to test your code, comments in-line:

JAVASCRIPT
1var assert = require('assert');
2
3function throttle(func, waitTime) {
4  // fiill in this method
5}
6
7let time = 0;
8
9function testThrottle(input) {
10  const calls = [];
11  time = 0;
12
13  function wrapper(arg) {
14    calls.push(`${arg}@${time}`);
15  }
16
17  const throttledFunc = throttle(wrapper, 3);
18  input.forEach((call) => {
19    const [arg, time] = call.split("@");
20    setTimeout(() => throttledFunc(arg), time);
21  });
22  return calls;
23}
24
25expect(testThrottle(["A@0", "B@2", "C@3"])).toEqual(["A@0", "C@3"]);

Question

Try to solve this here or in Interactive Mode.

How do I practice this challenge?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

We'll now take you through what you need to know.

How do I use this guide?