Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1ff4319

Browse files
author
Swastikyadav
committed
Add polyfills for debounce and throttle
1 parent 8559fdd commit 1ff4319

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

‎Polyfills/debounce.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/*
2+
- Debouncing is a technique to rate limit / reduce the number of requests to the server.
3+
- For example, when user types in an input, instead of sending request for every character typed, we send request only when user stops typing for a time period.
4+
- And if user starts typing again before given time period, we cancel the ongoing request and start new request.
5+
*/
6+
7+
function debounce(callback, delay) {
8+
let timerID;
9+
10+
return function(...args) {
11+
clearTimeout(timerID);
12+
13+
timerID = setTimeout(() => {
14+
callback.apply(this, args);
15+
}, delay);
16+
}
17+
}

‎Polyfills/throttle.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
## Throttling
3+
4+
- Similar technique to debouncing only difference being that request is sent every given number of seconds regardless of wheater user has stopped the action or not.
5+
- With every request we cancel the previous request timer.
6+
*/
7+
8+
function throttle(callback, delay) {
9+
let timerID;
10+
let lastTimeCalled = 0;
11+
12+
return function throttled(...args) {
13+
const currentTime = Date.now();
14+
const timeSinceLastCalled = currentTime - lastTimeCalled;
15+
const delayRemaining = delay - timeSinceLastCalled;
16+
17+
if (delayRemaining <= 0) {
18+
lastTimeCalled = Date.now();
19+
callback.apply(this, args);
20+
} else {
21+
clearTimeout(timerID);
22+
23+
timerID = setTimeout(() => {
24+
lastTimeCalled = Date.now();
25+
callback.apply(this, args);
26+
}, delayRemaining);
27+
}
28+
}
29+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /