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

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

问题描述

总是让我烦恼的是Javascript中的 setTimeout()方法是多么不可预测。

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

In根据我的经验,计时器在很多情况下非常不准确。由于不准确,我的意思是实际延迟时间似乎或多或少变化250-500ms。虽然这不是一个大量的时间,但当使用它来隐藏/显示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())。毫秒(或等价物)。这使您可以在较新的浏览器中利用更可靠的计时器支持,同时在旧版浏览器上仍能正常运行。

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天全站免登陆