liangbus / blogging

Blog to go
10 stars 0 forks source link

通过 setTimeout 模拟实现 setInterval #2

Open liangbus opened 5 years ago

liangbus commented 5 years ago

递归的方式实现

function mockInterval(fn, t){
  mockInterval.timer = setTimeout(() => {
    fn()
    mockInterval(fn, t)
  }, t)
}
YuetTong commented 2 years ago

[Ensure that execution duration is shorter than interval frequency] If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

In these cases, a recursive setTimeout() pattern is preferred

setTimeout 就是表示指定多少时间后 执行一个方法 至于setTimeout中执行的函数,在继续setTimeout调用本身 ,这个应该属于技巧 ,不属于setTimeout本身的含义,这样就明显区别于setInterval。

从效果上可以看出 setInterval 中调用的方法,不需要理会自己下次被调用会怎么样 iife

(function loop() { setTimeout(function () { // todo loop() }, delay) })()

一秒打印 (function loop() { setTimeout(function () { console.log(Date()); loop() }, 1000) })()