c55d96c3432b1a0051d42f4398787cf406a39857007a7421ce9ed7e07c674a94bb0569bdf25d79f151692a3f4c70bc4205e3f5f323fa4fde7fddb2f328fa7e 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. let lastTime = 0
  2. const prefixes = 'webkit moz ms o'.split(' ') // 各浏览器前缀
  3. let requestAnimationFrame
  4. let cancelAnimationFrame
  5. const isServer = typeof window === 'undefined'
  6. if (isServer) {
  7. requestAnimationFrame = function() {
  8. return
  9. }
  10. cancelAnimationFrame = function() {
  11. return
  12. }
  13. } else {
  14. requestAnimationFrame = window.requestAnimationFrame
  15. cancelAnimationFrame = window.cancelAnimationFrame
  16. let prefix
  17. // 通过遍历各浏览器前缀,来得到requestAnimationFrame和cancelAnimationFrame在当前浏览器的实现形式
  18. for (let i = 0; i < prefixes.length; i++) {
  19. if (requestAnimationFrame && cancelAnimationFrame) { break }
  20. prefix = prefixes[i]
  21. requestAnimationFrame = requestAnimationFrame || window[prefix + 'RequestAnimationFrame']
  22. cancelAnimationFrame = cancelAnimationFrame || window[prefix + 'CancelAnimationFrame'] || window[prefix + 'CancelRequestAnimationFrame']
  23. }
  24. // 如果当前浏览器不支持requestAnimationFrame和cancelAnimationFrame,则会退到setTimeout
  25. if (!requestAnimationFrame || !cancelAnimationFrame) {
  26. requestAnimationFrame = function(callback) {
  27. const currTime = new Date().getTime()
  28. // 为了使setTimteout的尽可能的接近每秒60帧的效果
  29. const timeToCall = Math.max(0, 16 - (currTime - lastTime))
  30. const id = window.setTimeout(() => {
  31. callback(currTime + timeToCall)
  32. }, timeToCall)
  33. lastTime = currTime + timeToCall
  34. return id
  35. }
  36. cancelAnimationFrame = function(id) {
  37. window.clearTimeout(id)
  38. }
  39. }
  40. }
  41. export { requestAnimationFrame, cancelAnimationFrame }