简体   繁体   English

使用Javascript优化现代浏览器(Chrome)的计时器

[英]Optimising timers for modern browsers (Chrome) in Javascript

I have written a web application which relies heavily on timers running in background tabs. 我编写了一个Web应用程序,该应用程序严重依赖于在后台选项卡中运行的计时器。 With the more recent Chrome browsers (>Chrome 57), the default option is for "expensive" timers to be throttled if they're in the background - I understand that this feature can be disabled in chrome://flags/ , but I want to avoid asking users to do this. 在更新的Chrome浏览器(> Chrome 57)中,默认选项是在后台使用“昂贵的”计时器进行调节-我知道可以在chrome://flags/禁用此功能,但我希望避免要求用户这样做。 An example of the timer is, which uses JQuery/JS and refreshes every second: 计时器的一个示例是,它使用JQuery / JS并每秒刷新一次:

function startTimer(seconds) {
  var timer = seconds - 1;
  var refresh = setInterval(function() { // refresh every second
    var output = displaySeconds(timer); // displaySeconds formats the time
    $("#timer").text(output);
    $("title").html(output + " - Timer");
    if (--timer < 0) {
      clearInterval(refresh); // exit refresh loop
    };
  }, 1000);

Often this timer is disrupted heavily by the browser and lasts about 50% longer than the seconds parameter given as input. 通常,此计时器会被浏览器严重破坏,并且其持续时间比输入的seconds参数长约50%。 I have also minified the JS, but understand that this only really reduces the size of the file so doesn't help. 我还缩小了JS的大小,但了解这只会真正减小文件的大小,因此无济于事。

What would be a sensible and browser agnostic way of optimising this to run smoothly in the background? 将其优化以在后台平稳运行的明智且与浏览器无关的方法是什么?

Ideas I have: - Find out when tab is in background using some relevant library, reduce the refresh rate to something more coarse (2 or 3 seconds) - seems complicated though! 我的想法:-使用一些相关的库找出选项卡在后台的时间,将刷新率降低到更粗糙的程度(2或3秒)-虽然看起来很复杂!

Thanks in advance 提前致谢

Two suggestions (largely in-line with your own solutions): 两个建议(主要与您自己的解决方案保持一致):

  • Make the timer dependent on the start-time. 使计时器取决于开始时间。 In that way, you won't be as dependent on the exact time that the timers fire: 这样,您将不再依赖计时器触发的确切时间:

(untested) (另)

function startTimer(seconds) {
    var endTime = new Date().valueOf() + seconds * 1000;
    var refresh = setInterval(function() { // refresh every second
    var now = new Date().valueOf(); // current time in ms
    var output = displaySeconds((endTime - now) / 1000); // displaySeconds formats the time
    $("#timer").text(output);
    $("title").html(output + " - Timer");
    if (now > endTime) {
      clearInterval(refresh); // exit refresh loop
    };
  }, 1000);

After applying that code, the GUI-updates could be wrapped in a if (doVisualUpdates) 应用该代码后,GUI更新可以包装在if (doVisualUpdates)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM