javascript / expert
Snippet
Optimizing Observable Streams with Custom AnimationFrameSchedulers
Using the animationFrameScheduler with observeOn ensures that the Observable emits values exactly when the browser is ready to paint the next frame. This prevents 'jank' in high-frequency events like scrolling or mouse movement by synchronizing logic with the browser's refresh rate.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { animationFrameScheduler, observeOn } from 'rxjs';@Component({ ... })export class ScrollMonitor {private scroll$ = fromEvent(window, 'scroll').pipe(observeOn(animationFrameScheduler));constructor() {this.scroll$.subscribe(() => this.updateParallax());}}
angular
Breakdown
1
fromEvent(window, 'scroll')
Creates a stream from a high-frequency browser event.
2
observeOn(animationFrameScheduler)
Defers the notification of emissions until the next requestAnimationFrame cycle.
3
this.updateParallax()
The logic executed here is now naturally throttled by the display refresh rate.