有没有比 setTimeout 更准确的方法来创建 Javascript 计时器? [英] Is there a more accurate way to create a Javascript timer than setTimeout?

查看:28
本文介绍了有没有比 setTimeout 更准确的方法来创建 Javascript 计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一直困扰我的是 JavaScript 中的 setTimeout() 方法是多么不可预测.

Something that has always bugged me is how unpredictable the setTimeout() method in Javascript is.

根据我的经验,计时器在很多情况下都非常不准确.不准确,我的意思是实际延迟时间似乎或多或少有 250-500 毫秒的变化.虽然这不是很长的时间,但是当使用它来隐藏/显示 UI 元素时,时间会很明显.

In my experience, the timer is horribly inaccurate in a lot of situations. By inaccurate, I mean the actual delay time seems to vary by 250-500ms more or less. Although this isn't a huge amount of time, when using it to hide/show UI elements the time can be visibly noticeable.

是否有任何技巧可以确保 setTimeout() 准确执行(无需求助于外部 API),或者这是一个失败的原因?

Are there any tricks that can be done to ensure that setTimeout() performs accurately (without resorting to an external API) or is this a lost cause?

推荐答案

有什么技巧可以做确保 setTimeout() 执行准确(不诉诸于外部 API)还是这是一个失败的原因?

Are there any tricks that can be done to ensure that setTimeout() performs accurately (without resorting to an external API) or is this a lost cause?

没有也没有.使用 setTimeout() 不会获得任何接近完美计时器的东西 - 浏览器没有为此设置.但是,您也不需要依赖它来计时.大多数动画库多年前就发现了这一点:您使用 setTimeout() 设置回调,但根据 (new Date()).milliseconds<的值确定需要执行的操作/code>(或等价物).这使您可以在较新的浏览器中利用更可靠的计时器支持,同时在较旧的浏览器上仍能正常运行.

No and no. You're not going to get anything close to a perfectly accurate timer with setTimeout() - browsers aren't set up for that. However, you don't need to rely on it for timing things either. Most animation libraries figured this out years ago: you set up a callback with setTimeout(), but determine what needs to be done based on the value of (new Date()).milliseconds (or equivalent). This allows you to take advantage of more reliable timer support in newer browsers, while still behaving appropriately on older browsers.

它还允许您避免使用太多计时器!这很重要:每个计时器都是一个回调.每个回调都执行 JS 代码.当 JS 代码正在执行时,浏览器事件——包括其他回调——被延迟或丢弃.当回调完成时,额外的回调必须与其他浏览器事件竞争执行的机会.因此,一个处理该时间间隔内所有待处理任务的计时器的性能将优于具有重合间隔的两个计时器,并且(对于短超时)优于具有重叠超时的两个计时器!

It also allows you to avoid using too many timers! This is important: each timer is a callback. Each callback executes JS code. While JS code is executing, browser events - including other callbacks - are delayed or dropped. When the callback finishes, additional callbacks must compete with other browser events for a chance to execute. Therefore, one timer that handles all pending tasks for that interval will perform better than two timers with coinciding intervals, and (for short timeouts) better than two timers with overlapping timeouts!

总结:停止使用setTimeout()来实现一个定时器/一个任务"的设计,并使用实时时钟来平滑UI动作.

Summary: stop using setTimeout() to implement "one timer / one task" designs, and use the real-time clock to smooth out UI actions.

这篇关于有没有比 setTimeout 更准确的方法来创建 Javascript 计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆