3

Seeing only 1st and last output of function call. Why ? And How to see the output of each function calling in a period of 1000ms?

Using lodash throttle.

const f = function (a) {
  console.log(a);
};

let f1000 = _.throttle(f, 1000);

f1000(1);
f1000(2);
f1000(3);
f1000(4);
f1000(5);
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
ElMuchacho
  • 300
  • 1
  • 12
  • From the docs: *"Creates a throttled function that only invokes `func` at most once per every `wait` milliseconds."* – Felix Kling Jun 07 '20 at 18:00

2 Answers2

2

First you have to understand that there are two moments for a timeout: leading and trailing. The first one is "the start" of the timeout and the second one is "the end" of the time out.

From the lodash docs:

Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the throttled function is invoked more than once during the wait timeout.

By default, they are true as you can see in the implementation here. This means that when invoking the same throttled function several times, it will invoke it once before the timeout starts and once after the timeout ends.

Also, note the following from the docs:

Subsequent calls to the throttled function return the result of the last func invocation.

Thus, your code snippet prints the first invocation because you call the throttled function several times and it's the leading edge of the timeout, doesn't invoke anything else because it's throttled, and finally returns the result of the latest invocation.

alexfertel
  • 925
  • 1
  • 9
  • 22
1

It throttles all the request that come up in the specified interval after invoking the first one (which prints 1) and Subsequent calls only return the result of the last invocation (which prints 5) after the interval is over. So, If you just do something like this, you'll see each of the values getting printed

const f = function (a) {
  console.log(a);
};

let f1000 = _.throttle(f, 1000);

setTimeout(()=>f1000(1), 1000)
setTimeout(()=>f1000(2), 2000)
setTimeout(()=>f1000(3), 3000)
setTimeout(()=>f1000(4), 4000)
setTimeout(()=>f1000(5), 5000)

Or, if you just reduce the throttle time to 0 milliseconds, it will print all the values.

const f = function (a) {
  console.log(a);
};

let f1000 = _.throttle(f, 0); //reduce throttle to 0


f1000(1);
f1000(2);
f1000(3);
f1000(4);
f1000(5);

I got this clue when I put a debugger in the function and kept the dev tool open. In that case it was printing each of the numbers (since, there was sufficient delay against each invocation). You can see this for yourself too.

const f = function (a) {
   debugger;
   console.log(a);
  };

Also, you might like to read the doc: https://lodash.com/docs/4.17.15#throttle

ABGR
  • 4,631
  • 4
  • 27
  • 49