1. export default class RAF {
    2. constructor () {
    3. this.init()
    4. }
    5. init () {
    6. this._timerIdMap = {
    7. timeout: {},
    8. interval: {}
    9. }
    10. }
    11. run (type = 'interval', cb, interval = 16.7) {
    12. const now = Date.now
    13. let stime = now()
    14. let etime = stime
    15. // 创建Symbol类型作为key值,保证返回值的唯一性,用于清除定时器使用
    16. const timerSymbol = Symbol('timerSymbol')
    17. const loop = () => {
    18. this.setIdMap(timerSymbol, type, loop)
    19. etime = now()
    20. if (etime - stime >= interval) {
    21. if (type === 'interval') {
    22. stime = now()
    23. etime = stime
    24. }
    25. cb()
    26. type === 'timeout' && this.clearTimeout(timerSymbol)
    27. }
    28. }
    29. this.setIdMap(timerSymbol, type, loop)
    30. return timerSymbol // 返回Symbol保证每次调用setTimeout/setInterval返回值的唯一性
    31. }
    32. setIdMap (timerSymbol, type, loop) {
    33. this._timerIdMap[type][timerSymbol] = requestAnimationFrame(loop)
    34. }
    35. setTimeout (cb, interval) { // 实现setTimeout 功能
    36. return this.run('timeout', cb, interval)
    37. }
    38. clearTimeout (timer) {
    39. cancelAnimationFrame(this._timerIdMap.timeout[timer])
    40. }
    41. setInterval (cb, interval) { // 实现setInterval功能
    42. return this.run('interval', cb, interval)
    43. }
    44. clearInterval (timer) {
    45. cancelAnimationFrame(this._timerIdMap.interval[timer])
    46. }
    47. }