手写系列 # 2:利用 requestAnimationFrame 实现 setInterval 计时器

简介: 手写系列 # 2:利用 requestAnimationFrame 实现 setInterval 计时器

实现

const kaimo = {
  timer: null,
  setInterval: function (callback, interval) {
    // 起始时间
    let startTime = new Date().valueOf();
    // 结束时间
    let endTime = new Date().valueOf();
    const self = this;
    // 循环函数
    const loop = function() {
      // 该方法调用必须在 callback 之前,确保打印的 'self.timer'  'clearInterval' 的值一样
      self.timer = requestAnimationFrame(loop);
      endTime = new Date().valueOf();
      // 判断时间超过 interval 就执行函数,并重置时间
      if(endTime - startTime >= interval) {
        // 让起始时间、结束时间相同
        endTime = startTime = new Date().valueOf();
        // 执行回调
        console.log('self.timer', self.timer);
        callback && callback();
      }
    }
    // 执行 requestAnimationFrame
    this.timer = requestAnimationFrame(loop);
    console.log('timer', this.timer);
    // 返回 timer
    return this.timer;
  },
  clearInterval: function () {
    console.log('clearInterval', this.timer);
    cancelAnimationFrame(this.timer);
  }
};



测试

// 测试 3秒后清掉
let count = 0;
kaimo.setInterval(() => {
  console.log(666);
  count++;
  if(count >= 3) {
    kaimo.clearInterval();
  }
}, 1000);

5a9f96b292af4e24aeeac2e4a7e56f23.png

目录
相关文章
|
4月前
|
JavaScript 前端开发
JS实现可以控制的定时器,setInterval,clearInterval
JS实现可以控制的定时器,setInterval,clearInterval
20 0
|
4月前
|
前端开发 JavaScript API
2022年了!还在用定时器实现动画?赶紧试试requestAnimationFrame吧!
2022年了!还在用定时器实现动画?赶紧试试requestAnimationFrame吧!
|
5月前
14 # 手写 debounce 防抖方法
14 # 手写 debounce 防抖方法
24 1
setInterval与clearInervar实现秒表功能
setInterval与clearInervar实现秒表功能
|
JavaScript API
js:定时器setInterval、clearInterval的使用
js:定时器setInterval、clearInterval的使用
111 0
|
JavaScript 前端开发
js 定时器用法详解——setTimeout()、setInterval()、clearTimeout()、clearInterval()
写在前面: 在js应用中,定时器的作用就是可以设定当到达一个时间来执行一个函数,或者每隔几秒重复执行某段函数。这里面涉及到了三个函数方法:setInterval()、setTimeout()、clearInterval(),本文将围绕这三种函数的用法,来实现定时器的功能,需要的朋友可以过来参考下,喜欢的可以点波赞,或者关注一下本人,希望对大家有所帮助。 定时器的应用需求: 1.设定一个时间,当时间到达的时候执行函数————比如:倒计时跳转页面等等。 2.每隔一段时间重复执行某段函数————比如抢票软件,比如设定500毫秒就重复刷新一次页面等等。 倒计时跳转实现demo:
535 0
js 定时器用法详解——setTimeout()、setInterval()、clearTimeout()、clearInterval()
|
JavaScript 前端开发 异构计算
requestAnimationFrame 和 setInterval 在动画上应用的区别
定义 requestAnimationFrame 帧动画,又叫 RAF,在 requestAnimationFrame 中执行的事件叫 RAF 回调 setInterval 引用 MDN 的定义 区别
15、计时器方法1(setInterval、clearInterval)
15、计时器方法1(setInterval、clearInterval)
104 0
16、计时器方法2(setTimeout、clearTimeout、防抖、节流)
16、计时器方法2(setTimeout、clearTimeout、防抖、节流)
95 0
|
JavaScript
BOM 定时器:setTimeout和setInterval
BOM 定时器:setTimeout和setInterval
157 0