jQuery setInterval从实时延迟

jQuery setInterval delays from real time

本文关键字:延迟 实时 setInterval jQuery      更新时间:2023-09-26

是否有可能使setInterval与当前时间一起工作?

我的意思是,我正在制作一个自定义的倒计时库供个人使用,我需要计算每秒,但有时setInterval从实时延迟,我认为这是因为浏览器滞后或执行时间。或者还有其他更好的方法吗?

函数的执行时间示例,即使有1000毫秒,时间也可能变化:

start: 898, end: 898, execution time: 0 index.js:92 start: 898, end: 899, execution time: 1 index.js:92 start: 899, end: 900, execution time: 1 index.js:92 start: 900, end: 901, execution time: 1 index.js:92 start: 904, end: 905, execution time: 1 index.js:92 start: 904, end: 905, execution time: 1 index.js:92 start: 905, end: 905, execution time: 0 index.js:92 start: 905, end: 905, execution time: 0 index.js:92 start: 906, end: 906, execution time: 0 index.js:92 start: 906, end: 907, execution time: 1 index.js:92 start: 892, end: 892, execution time: 0 index.js:92 start: 907, end: 907, execution time: 0 index.js:92 start: 907, end: 908, execution time: 1 index.js:92 start: 908, end: 908, execution time: 0 index.js:92 start: 908, end: 909, execution time: 1 index.js:92 start: 909, end: 910, execution time: 1 index.js:92

不要在开始时计算秒数,并尝试每隔一秒减少一秒。

相反,计算出结束时间,然后在setInterval/setTimeout的每一次滴答(这可能应该比每秒一次更频繁),计算当前时间和结束时间之间的时间量

如果"浏览器延迟"是问题所在,你可以设置一个网络工作者来计时并触发主页上的某些事件。

这是一个很大的开销,因为webworker是相当昂贵的,但可以帮助你。