Skip to content

Instantly share code, notes, and snippets.

@dmail
Last active March 28, 2018 12:29
Show Gist options
  • Save dmail/05e37928eeaf88ebfd60b9142a83a6e0 to your computer and use it in GitHub Desktop.
Save dmail/05e37928eeaf88ebfd60b9142a83a6e0 to your computer and use it in GitHub Desktop.
Utility to ensure UI mutations are executed together
export const batchUIMutation = (fnMutatingUI) => {
if (typeof window !== 'undefined' && window.requestAnimationFrame) {
const id = requestAnimationFrame(() => {
cancelAnimationFrame(id)
fnMutatingUI()
})
return () => cancelAnimationFrame(id)
}
const id = setTimeout(() => {
clearTimeout(id)
fnMutatingUI()
}, 17)
return () => clearTimeout(id)
}
import { batchUIMutation } from "./batch-ui-mutations.js"
// in browsers supporting requestAnimationFrame mutations on body.style below
// will be batched by browser to trigger only one repaint/reflow
// inside other browsers, they will be grouped thanks to setTimeout without benefits of requestAnimationFrame
batchUIMutation(() => {
document.body.style.color = "red"
})
batchUIMutation(() => {
document.body.style.paddingTop = "10px"
})
// please note each call to batchUIMutation can be cancelled as shown below
const cancel = batchUIMutation(() => {
document.body.style.paddingLeft = "10px"
})
cancel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment