Skip to content

Commit 4d399b6

Browse files
authored
Рефакторит обработчик скролла для header (#1330)
1 parent d67ef2d commit 4d399b6

File tree

2 files changed

+15
-19
lines changed

2 files changed

+15
-19
lines changed

src/scripts/libs/throttle.js

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,21 @@
1-
export default function throttle(callback, delay, options = { leading: true }) {
2-
let isThrottled = false
1+
export default function throttle(callback) {
2+
let requestId = null
33
let savedArgs
44
let savedThis
55

6-
return function wrapper() {
7-
if (isThrottled) {
8-
savedArgs = arguments
9-
savedThis = this
10-
return
11-
}
12-
13-
options.leading && callback.apply(this, arguments)
6+
function frameFunction() {
7+
callback.apply(savedThis, savedArgs)
8+
requestId = null
9+
}
1410

15-
isThrottled = true
11+
function replacedFunction() {
12+
savedThis = this
13+
savedArgs = arguments
1614

17-
setTimeout(function () {
18-
isThrottled = false
19-
if (savedArgs) {
20-
callback.apply(savedThis, savedArgs)
21-
savedArgs = savedThis = null
22-
}
23-
}, delay)
15+
if (requestId === null) {
16+
requestId = requestAnimationFrame(frameFunction)
17+
}
2418
}
19+
20+
return replacedFunction
2521
}

src/scripts/modules/header.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class Header extends BaseComponent {
8383
})
8484

8585
document.addEventListener('keyup', this.openOnKeyUp)
86-
window.addEventListener('scroll', throttle(this.checkSticky, { leading: false }), { passive: true })
86+
window.addEventListener('scroll', throttle(this.checkSticky))
8787

8888
this.checkSticky()
8989
}

0 commit comments

Comments
 (0)