Jon*_*son 5 javascript google-chrome settimeout
我有一个webapp,使用setTimeout播放带淡入/淡出过渡的音频.众所周知,chrome和其他浏览器在非活动(或背景)选项卡中运行时会限制setTimeout执行.因此,要解决此问题,我使用此脚本(https://github.com/turuslan/HackTimer)修补Timer API以使用Web Worker.这允许音量衰落转换在后台运行,这样无论选项卡是否处于活动状态,它们将始终在同一时间执行和完成.这曾经在chrome中运行得很好,但现在我注意到在版本54(可能还有早期版本)的chrome中,Web Workers在非活动选项卡中运行时的执行速度是原来的两倍.这个问题不会发生,并且与FireFox甚至IE11完美配合!
这是一个铬虫吗?还是打算行为?这个问题还有另一种解决方法吗?我不想要求在单独的窗口中打开webapp,因此这不是一个选项.
这是一个演示:https: //jsfiddle.net/2614xsj8/1/
// Open Chrome console and run this then wait a few seconds to see
// it is executing on time. Then open or switch to a new tab and wait
// a few seconds. Come back to see how much slower the setTimeout
// function was being called even when using HackTimer which patches
// the Timer API to use Web Workers
var rate = 1000;
var start = new Date().getTime();
var func = function() {
var now = new Date().getTime();
var time = now - start;
var status = Math.abs(rate - time) <= 50 ? "on time" : (time / rate) + " times slower";
console.log("executed in [" + time + "] milliseconds. " + status);
start = now;
setTimeout(func, rate);
};
setTimeout(func, rate);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.rawgit.com/turuslan/HackTimer/master/HackTimer.js" type="text/javascript"></script>Run Code Online (Sandbox Code Playgroud)
使用任务计划程序将是最好的方法,那么您实际上不会超时或间隔,而是特定的日期
但这需要使用服务人员来代替......这是一个令人遗憾的事情。因为那么您的网站还需要列入白名单才能运行服务工作人员(因此您的网站需要有效的 SSL 证书)
// https://example.com/serviceworker.js
this.ontask = function(task) {
alert(task.data.message);
console.log("Task scheduled at: " + new Date(task.time));
// From here on we can write the data to IndexedDB, send it to any open windows,
// display a notification, etc.
}
// https://example.com/webapp.js
function onTaskAdded(task) {
console.log("Task successfully scheduled.");
}
function onError(error) {
alert("Sorry, couldn't set the alarm: " + error);
}
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
serviceWorkerRegistration.taskScheduler.add(Date.now() + (10 * 60000), {
message: "It's been 10 minutes, your soup is ready!"
}).then(onTaskAdded, onError);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
824 次 |
| 最近记录: |