SetTimeout(延迟计时器-最小延迟)

本文探讨了浏览器中setTimeout和setInterval的最小延迟机制,介绍了利用window.postMessage实现0ms延迟定时器的方法,并通过示例展示了如何在React中运用消息通道进行时间切片。重点讲解了如何避免延迟累积和实现高性能定时器。

setTimeout 是有最小延迟时间?

 

  • MDN 文档 setTimeout

    • 实际延时比设定值更久的原因:最小延迟时间

    • 在浏览器中,setTimeout()/setInterval() 的每调用一次定时器的最小间隔是 4ms,这通常是由于函数嵌套导致(嵌套层级达到一定深度)。

  • HTML Standard

    • Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.

    • (定时器可以嵌套;然而,在五个这样的嵌套定时器之后,间隔被强制为至少四毫秒。)

  • 示例测试

  •   let a = performance.now();

      setTimeout(() => {

        let b = performance.now();

        console.log(b - a);

        setTimeout(() => {

          let c = performance.now();

          console.log(c - b);

          setTimeout(() => {

            let d = performance.now();

            console.log(d - c);

            setTimeout(() => {

              let e = performance.now();

              console.log(e - d);

              setTimeout(() => {

                let f = performance.now();

                console.log(f - e);

                setTimeout(() => {

                  let g = performance.now();

       &

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值