Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

通过 setTimeout 模拟实现 setInterval #2

Open
liangbus opened this issue Oct 24, 2019 · 1 comment
Open

通过 setTimeout 模拟实现 setInterval #2

liangbus opened this issue Oct 24, 2019 · 1 comment

Comments

@liangbus
Copy link
Owner

递归的方式实现

function mockInterval(fn, t){
  mockInterval.timer = setTimeout(() => {
    fn()
    mockInterval(fn, t)
  }, t)
}
@YuetTong
Copy link

YuetTong commented Mar 3, 2022

[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)
})()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants