Created
March 29, 2021 02:16
-
-
Save wewindy/72b023e169c9e93ed839256b79600fe5 to your computer and use it in GitHub Desktop.
能用时间和条件来控制 requestAnimationFrame 的渲染
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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