又到了金三银四的季节了,面试的各位同学要开始准备起来了,今天主要分享一个在面试中经常被提到的一个面试题:倒计时。其实这个问题不仅是在面试中,也在我们的业务里也会经常用到,所以到底如何才能写好一个倒计时呢?
首先我们在写倒计时的时候必须要考虑到三点:准确性、稳定性、性能。接下来我们来一步一步实现一个准确的定时器。
setinterval
我们先来简单实现一个倒计时的函数:
function example1(lefttime){ let t = lefttime; setinterval(() => { t = t - 1000; console.log(t); }, 1000); } example1(10);
可以看到使用setinterval即可,但是setinterval真的准确吗?我们来看一下mdn中的说明:
如果你的代码逻辑执行时间可能比定时器时间间隔要长,建议你使用递归调用了settimeout 的具名函数。例如,使用 setinterval()
以 5 秒的间隔轮询服务器,可能因网络延迟、服务器无响应以及许多其他的问题而导致请求无法在分配的时间内完成。
简单来说意思就是,js因为是单线程的原因,如果前面有阻塞线程的任务,那么就可能会导致setinterval函数延迟,这样倒计时就肯定会不准确,建议使用settimeout替换setinterval。
settimeout
按照上述的建议将setinterval换为settimeout后,我们来看下代码:
function example2(lefttime) { let t = lefttime; settimeout(() => { t = t - 1000; if (t > 0) { console.log(t); example2(t); } console.log(t); }, 1000); }
mdn中也说了,有很多因素会导致 settimeout 的回调函数执行比设定的预期值更久,比如嵌套超时、非活动标签超时、追踪型脚本的节流、超时延迟等等,详情见developer.mozilla.org/zh-cn/docs/web/api/settimeout,总就就是和setinterval差不多,都可能会有延迟执行的时候,这么一来如何提高倒计时的准确性呢?
requestanimationframe
这里就不得不提一个新的方法requestanimationframe,它是一个浏览器 api,允许以 60 帧/秒 (fps) 的速率请求回调,而不会阻塞主线程。通过调用 requestanimationframe 方法浏览器会在下一次重绘之前执行指定的函数,这样可以确保回调在每一帧之间都能够得到适时的更新。
我们使用requestanimationframe结合settimeout来优化一下之前的代码:
function example3(lefttime) { let t = lefttime; function start() { requestanimationframe(() => { t = t - 1000; settimeout(() => { console.log(t); start(); }, 1000); }); } start(); }
这样的话就可以保证我们倒计时的稳定性,使用requestanimationframe还有一个好处就是,息屏或者切后台的操作时,requestanimationframe是不会继续调用函数的,但是如果只使用settimeout或者setinterval的话,他们会在后台一直执行,显而易见,requestanimationframe更加的节省性能开销。
在切后台或者息屏的实际执行时会发现,虽然性能上好了,但上述的方法在准确性上确出了问题,当回到页面时,倒计时会接着切后台时的时间执行,这样肯定是不对。
difftime
要解决上述的问题,通过时间差值每次进行对比就可以了。
function example4(lefttime) { const now = new date().gettime(); function start() { requestanimationframe(() => { const diff = lefttime - (new date().gettime() - now); settimeout(() => { console.log(diff); start(); }, 1000); }); } start(); }
上面的代码实现思路其实在实际的业务中已经能够满足我们的使用场景,但是如果想要在面试的时候表现的再好一点其实还是有可以优化空间的,那么还要怎么优化呢?
finally
我们来仔细分析一下,如上图所示,上面代码每次在settimeout时其实真正执行的时间不可能完全是一秒,可能多也可能少,这样时间一长之后执行到结束时肯定会和实际时间有误差,虽然在秒级的单位不一定能看出来,如果采用毫秒做单位的话肯定会有些许。那么应该如何处理呢?
其实最终的实现思路有也很简单,在每次在执行settimeout的时候,不要将每次settimeout的时间都设置为1000ms,而是算出每次执行实际settimeout中执行的函数话费的时间,根据实际执行的时间算出下次settimeout需要执行的时间即可。至于下次执行的时间应该怎么算呢?我们来通过简单的一个图表来找出其中的规律,假设下图是每次settimeout执行的时间分布图所示:
time时间 | executiontime实际执行时间 | difftime差值 | nexttime下次执行时间 |
---|---|---|---|
0 | 1200 | 200 | 1000 |
1000 | 900 | 100 | 900 |
2000 | 900 | 0 | 1000 |
3000 | 800 | 200 | 1200 |
4000 | 1300 | 100 | 900 |
… | … | … | … |
通过上面的图表我们可以发现 nexttime = executiontime > nexttime ? 1000 - difftime : 1000 + difftime。
还需要注意的时候,一般在实际业务时后端返回给我们剩余时间字段,通常都不会是整秒的,这样我们第一次执行settimeout的时的执行时间就需要处理一下,在倒计时最后结束时可以大大减少最终的时间误差。
根据上述的思路我们来看一下最终封装出来的react hooks:
const usecountdown = ({ lefttime, ms = 1000, onend }) => { const countdowntimer = useref(); const starttimer = useref(); const starttimeref = useref(new date().gettime()); const nexttimeref = useref(lefttime % ms); const [count, setcount] = usestate(lefttime); const cleartimer = () => { countdowntimer.current && cleartimeout(countdowntimer.current); starttimer.current && cleartimeout(starttimer.current); }; const startcountdown = () => { cleartimer(); const currenttime = new date().gettime(); // 每次实际执行的时间 const executiontime = currenttime - starttimeref.current; // 实际执行时间大于上一次需要执行的时间,说明执行时间多了,差值为多出来的时间,否则为少了的时间 const difftime = executiontime > nexttimeref.current ? executiontime - nexttimeref.current : nexttimeref.current - executiontime; // 剩余时间减去应该执行的时间 setcount((count) => { const c = count - (count % ms === 0 ? ms : count % ms); if (c <= 0) return 0; return c; }); // 算出下一次的时间 思路:本次的实际执行时间>下一次执行的时间 ?1000 - difftime : 1000 + difftime; nexttimeref.current = executiontime > nexttimeref.current ? ms - difftime : ms + difftime; // 重置初始时间 starttimeref.current = new date().gettime(); countdowntimer.current = settimeout(() => { requestanimationframe(startcountdown); }, nexttimeref.current); }; useeffect(() => { setcount(lefttime); starttimer.current = settimeout( startcountdown, nexttimeref.current, ); return () => { cleartimer(); }; }, [lefttime]); useeffect(() => { if (count <= 0) { cleartimer(); onend && onend(); } }, [count]); return count; }; export default usecountdown;
除了上述的优化思路,欢迎大家有更好的想法也可以随时进行探讨~
到此这篇关于js面试必备之如何实现一个精确的倒计时的文章就介绍到这了,更多相关js倒计时内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网
发表评论