You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// 阻塞线程setInterval(function(){varj=0;while(j++<1000000000);console.log('setInterval')},0)varinterval=1000// 间隔,单位 msvarexpected=Date.now()+intervalsetTimeout(step,interval)functionstep(){vardt=Date.now()-expected// the drift (positive for overshooting) if(dt>interval){// something really bad happened. Maybe the browser (tab) was inactive?// possibly special handling to avoid futile "catch up" run}// do what is to be doneexpected+=intervalsetTimeput(step,Math,max(0,interval-dt))// take into account drift}
JavaScript 实现精准定时 —— self-adjusting timers 自动调节定时器
JavaScript 由于事件循环的问题,宏任务都可能会被推迟。当遇到一个占用线程很久的代码,使用定时器就会被往后推迟
所以,我们需要来修正这些因为执行时间超长的代码带来的定时器的延后问题。
可以来做一个 自动调节定时器 ( self - adjusting timers) 来消除定时不准的问题,当然还是会有毫秒级的延时,不会完全没有的。
setTimeout 递归实现
这里找了两个版本,看起来都还可以
版本一 超高精度的秒杀倒计时
原理是倒计时前记录当前时间
t1
,递归时记录递归次数c1
,每一次递归时,用当前时间t2
- (t1
+c1
*interval
) 得到是误差时间offset
,使用interval
-offset
即可得到下一个setTimeout
的时间。(我并没有懂是怎么出来的这个公式)版本二 How to create an accurate timer in javascript?
秒杀场景下的倒计时
秒杀场景由于客户端的时间是不一致的,所以需要用服务端的时间来统一倒计时。
原理:客户端根据活动开始时间和服务器时间差做倒计时显示.用一个定时器定时,用另一个定时器更新时间变量,进行修正。
The text was updated successfully, but these errors were encountered: