Skip to content

Commit 2dddb62

Browse files
committed
pref: add throttle to IntersectionObserver
1 parent f801e18 commit 2dddb62

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/utils/lazy-load.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,34 @@ class LazyLoader {
22
private el: HTMLElement
33
private handler: () => void
44
private intersectionObserver!: IntersectionObserver
5+
private timer: NodeJS.Timeout | null
6+
private rended: boolean
57

68
constructor(el: HTMLElement, handler: () => void) {
79
this.el = el
810
this.handler = handler
11+
this.timer = null
12+
this.rended = false
913
}
1014

1115
public observe() {
1216
const cb = (entries: IntersectionObserverEntry[]) => {
17+
if (this.rended) return this.unobserve()
18+
1319
const entry = entries[0]
14-
if (entry.intersectionRatio > 0) this.handler()
20+
21+
if (entry.intersectionRatio > 0) {
22+
this.timer = setTimeout(() => {
23+
this.handler()
24+
this.rended = true
25+
console.log(this.rended)
26+
}, 260)
27+
} else {
28+
if (this.timer) {
29+
clearTimeout(this.timer)
30+
this.timer = null
31+
}
32+
}
1533
}
1634

1735
this.intersectionObserver = new IntersectionObserver(cb)

0 commit comments

Comments
 (0)