Javascript Timed Notifications - setTimeout, setInterval

谁都会走 提交于 2019-12-04 12:33:28

My question is, will having multiple setTimeouts (10+) running in the background during user interaction slow down the performance of my app?

In those numbers, no. (Depending on how + the + in 10+ is. I mean, I expect a million probably would be an issue.)

The other approach would be to have a single timer that you use (say, per minute) to check for notifications that should occur as of that minute. E.g.:

function notifyForThisMinute() {
    // Notify user of things we should notify them of as of this minute
    // ...

    // Schedule next check for beginning of next minute; always wait
    // until we're a second into the minute to make the checks easier
    setTimeout(notifyForThisMinute, (61 - new Date().getSeconds()) * 1000);
}
notifyForThisMinute(); // First call starts process

This depends on the browser (or more specifically, it's javascript engine) and apparently even OS.

Neil Thomas (while working on GMAIL mobile) and John Resig have analyzed timers.

One of the more noticeable things to look out for is how often the timer runs per given time-interval (say every 200ms or once every 10 minutes..).

Thomas:

With low-frequency timers - timers with a delay of one second or more - we could create many timers without significantly degrading performance on either [an Android G1 or iPhone 3G]. Even with 100 timers scheduled, our app was not noticeably less responsive. With high-frequency timers, however, the story was exactly the opposite. A few timers firing every 100-200 ms was sufficient to make our UI feel sluggish.

Thomas:

Keep in mind that this code is going to execute many times every second. Looping over an array of registered callbacks might be slightly "cleaner" code, but it's critical that this function execute as quickly as possible. Hardcoding the function calls also makes it really easy to keep track of all the work that is being done within the timer.

Resig:

Once you start moving into the range of 64-128 simultaneous timers, you’re pretty much out of luck in most browsers.

One might also have a look at Chronos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!