2021-06-22

手写js中setTimerOut功能

用原生setTimerOut和手写setTimerOut进行比较,可以让同学们更加深刻理解js
原生setTimerOut

   setTimeout(function (a, b) {
           console.log('我执行了');
           console.log('参数a', a);
           console.log(b);
         }, 2000, 'dddd', 123);

手写setTimerOut

  // 1:求当前时间的时间戳 
        var now = new Date().getTime();
        // 2:求未来时间的时间戳 

        function setTimeZA(callback, time,a) {
            // 获取计时器执行时间。
            var now = new Date().getTime();
            // 求 回调函数 将来在什么时间执行
            var out = now + time;
            // 如何实时监听时间的变化
            var timer = setInterval(function () {
                var timeout = new Date().getTime();
                // 用监听的时间,与 程序将来执行的时间进行比较。
                if (timeout >= out) {
                    clearInterval(timer)
                    // 当时间到了2000后,让 callback执行
                    callback(a);
                }
            }, 0)
        }
        setTimeZA(function (a) {
            console.log('=================================');
            console.log('zhangao');
            console.log(a);
        }, 500,'dfsadf')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值