Skip to content

Instantly share code, notes, and snippets.

@wewindy
Created March 29, 2021 02:16
Show Gist options
  • Save wewindy/72b023e169c9e93ed839256b79600fe5 to your computer and use it in GitHub Desktop.
Save wewindy/72b023e169c9e93ed839256b79600fe5 to your computer and use it in GitHub Desktop.
能用时间和条件来控制 requestAnimationFrame 的渲染
function main() {
let last = 0
// 上次渲染的值(此处初始化为一个整数)
let lastState = Math.floor(Math.random() * 10)
const canWeRender = function() {
// 这次渲染的值
const currentState = Math.floor(Math.random() * 10)
// 比较二者是否一致,如果一致,则false,否则true
if (currentState === lastState) {
console.log("lastState eq. currentState. Will not render.")
return false
} else {
lastState = currentState
return true
}
}
const TIME_STEP = 500
function render(time) {
if (time - last > TIME_STEP && canWeRender()) {
console.log('rendered.')
last = time
}
requestAnimationFrame(render)
}
render()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment