1: 概念:
告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。(默认1s执行60次)60HZ
2: 方法:
1: window.requestAnimationFrame(cb); // 执行回调
2: window.cancelAnimatinFrame(id); // 清除方法
var oShow = document.getElementsByClassName('show')[0]; oRemove = document.getElementById('remove'); let anId = null, speed = 5, // 一秒执行多少次 t = null, str = 'qwertyuiopasdfghjklzxcvbnm', requestAnimatinoFrame = window.requestAnimationFrame; let flag = true; const init = function () { onRequestAnimationFranme(); oRemove.addEventListener('click', onRemoveAnimation, false) } function onRequestAnimationFranme() { t = setTimeout(() => { // 调用指定的回调函数onRequestAnimationFranme anId = requestAnimatinoFrame(onRequestAnimationFranme) // 重新执行回调 // 随机索引 let idx = Math.floor((Math.random() * str.length)); // 随机单词 let word = str[idx]; oShow.innerText = word; }, 1000 / speed) } function onRemoveAnimation () { console.log(11); clearTimeout(t); t = null; window.cancelAnimationFrame(anId); anId = null; } init()