1: 概念:

  1. 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。(默认1s执行60次)60HZ

2: 方法:

1: window.requestAnimationFrame(cb); // 执行回调

2: window.cancelAnimatinFrame(id); // 清除方法

  1. var oShow = document.getElementsByClassName('show')[0];
  2. oRemove = document.getElementById('remove');
  3. let anId = null,
  4. speed = 5, // 一秒执行多少次
  5. t = null,
  6. str = 'qwertyuiopasdfghjklzxcvbnm',
  7. requestAnimatinoFrame = window.requestAnimationFrame;
  8. let flag = true;
  9. const init = function () {
  10. onRequestAnimationFranme();
  11. oRemove.addEventListener('click', onRemoveAnimation, false)
  12. }
  13. function onRequestAnimationFranme() {
  14. t = setTimeout(() => {
  15. // 调用指定的回调函数onRequestAnimationFranme
  16. anId = requestAnimatinoFrame(onRequestAnimationFranme)
  17. // 重新执行回调
  18. // 随机索引
  19. let idx = Math.floor((Math.random() * str.length));
  20. // 随机单词
  21. let word = str[idx];
  22. oShow.innerText = word;
  23. }, 1000 / speed)
  24. }
  25. function onRemoveAnimation () {
  26. console.log(11);
  27. clearTimeout(t);
  28. t = null;
  29. window.cancelAnimationFrame(anId);
  30. anId = null;
  31. }
  32. init()