Loktar が示唆したように、この症状は、時間を確認し、自分がどこにいるべきかを把握することで軽減できます. これを行うことができる関数は次のとおりです。
function smartInterval(func, interval){
var last = new Date() - interval,
now,
numMissed;
(function iterate(){
func();
// compute the number of iterations you might have missed
// if you tabbed away and the interval was restricted to 1000ms
now = +new Date();
numMissed = Math.round((now - last) / interval) - 1;
// make up for those iterations that were lost
while (numMissed--) { func(); }
last = +new Date();
setTimeout(iterate, interval);
})();
}
使用法:
smartInterval(function(){console.log('hi');}, 100);
例を含む jsFiddle を次に示します。while
ループ ( )をコメントアウトしてwhile (numMissed--)
、タブに切り替えると数値が少なくなることを確認してください。while
ただし、そこにループがあると、間隔がまったく変わっていないように見えます。
残念ながら、Processing.js を使用しており、タイムアウトは内部で設定されているため、これは役に立たない可能性があります。