Skip to content

Instantly share code, notes, and snippets.

@f0rr0
Last active January 13, 2017 13:19
Show Gist options
  • Save f0rr0/93e42d1fd7440ec7a61b480a4d05c764 to your computer and use it in GitHub Desktop.
Save f0rr0/93e42d1fd7440ec7a61b480a4d05c764 to your computer and use it in GitHub Desktop.
Raf throttle a function
// Comparison b/w rx-raf-throttle and myRafThrottle
// Copy-paste at https://esnextb.in to run
// Expected output is both fn get called together roughly
import {Observable as O} from 'rx'
import {rxRAFThrottle} from 'rx-raf-throttle'
const rafThrottle = f => {
let rendering = false
let _val
const callback = () => {
rendering = true
f(_val)
rendering = false
}
return val => {
_val = val
if (!rendering) {
requestAnimationFrame(callback)
}
}
}
const INTERVAL = 1 // in ms
const t = O.interval(INTERVAL)
const helper = fn => {
let counter = 0
const timer = setInterval(() => {
fn(counter)
counter++
}, INTERVAL)
}
t.subscribe(x => document.writeln(x + '<br/>'))
helper(x => document.writeln(x + '<br/>'))
rxRAFThrottle(t).subscribe(x => document.writeln('rxRaf(' + x + ')<br/>'))
helper(rafThrottle(x => document.writeln('myRaf(' + x + ')<br/>')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment