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

关于不准确的定时器的修正 #73

Open
vanishcode opened this issue Nov 13, 2018 · 0 comments
Open

关于不准确的定时器的修正 #73

vanishcode opened this issue Nov 13, 2018 · 0 comments

Comments

@vanishcode
Copy link
Owner

vanishcode commented Nov 13, 2018

// 修正settimeout
var startTime = new Date().getTime();
var count = 0;

// 模拟延时任务
setInterval(function () {
    var i = 0;
    while (i++ < 10000);
}, 0);

/* 
* 原理:不考虑误差,每次递归,count加一,所以期望当前时间对应是count*1000,相减就是误差,
* 就是相对于正确时间“慢了的”,所以在下次调用自身时应该把这个减去,做到“提前”
*/

function fixed() {
    count++;
    var offset = new Date().getTime() - (startTime + count * 1000);
    var nextTime = 1000 - offset;
    if (nextTime < 0) nextTime = 0;
    setTimeout(fixed, nextTime);
    console.log(new Date().getTime() - (startTime + count * 1000));
}
setTimeout(fixed, 1000);

其实抛开第一个延时模拟,误差不是特别大,但是实际情况中基本上肯定比这个要多,这个只是做到了不累加,所以误差基本上会根据用户情况稳定在某一范围,这样其实基本满足生产要求了。

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

No branches or pull requests

1 participant