requestAnimationFrame.js 1.4 KB

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