forked from Tinkoff/utils.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththrottleEnd.ts
More file actions
36 lines (32 loc) · 1013 Bytes
/
throttleEnd.ts
File metadata and controls
36 lines (32 loc) · 1013 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import curryN from './curryN';
import { throttleEnd } from '../typings/types';
/**
* Creates a throttled function that only invokes `fn` at most once per
* every `wait` milliseconds. `fn` is called in the end of `wait` delay
*
* @param {number} wait The number of milliseconds to throttle invocations to.
* @param {Function} fn The function to throttle.
*/
export default curryN(2, (wait, fn) => {
let lastCalled;
let lastArgs;
let lastThis;
let timeout;
return function (...args) {
const now = Date.now();
const diff = lastCalled + wait - now;
if (diff < 0 && timeout) {
clearTimeout(timeout);
timeout = null;
fn.apply(this, args);
} else if (!timeout) {
timeout = setTimeout(() => {
fn.apply(lastThis, lastArgs);
timeout = null;
}, wait);
}
lastCalled = now;
lastArgs = args;
lastThis = this;
};
}) as typeof throttleEnd