カウントダウンは、ウィンドウがアクティブなときだけカウントダウンし、ウィンドウがアクティブでなくなるたびに停止するようにしようとしています。
私はこのプラグインを使用しています: https://github.com/mathiasbynens/jquery-visibility/blob/master/jquery-visibility.js
$(function() {
$(document).on({
'show.visibility': function() {
setTimeout("runCounter()",1000);
console.log('The page gained visibility; the <code>show</code> event was triggered.');
},
'hide.visibility': function() {
time = time;
console.log('The page lost visibility; the <code>hide</code> event was triggered.');
}
});
});
function runCounter() {
if(time==0){
$('#counter').html('<button class="butn blue" onclick="<?php echo $creditButtonName; ?>();">Click here to get credited!</button>');
}
else {
$('#counter').html('You must view this advertisement for ' + time + ' more seconds!');
startBar();
time=time-1;
//setTimeout("runCounter()",1000);
}
}
jquery 可視性 API を 1 回だけではなく、ページがアクティブなときに 1 秒ごとに実行し、ページがアクティブでないときに別の関数をトリガーする方法を教えてください。
この現在の状態では、これsetTimeout("runCounter()",1000);
は、別のウィンドウ/タブに移動してから最初のウィンドウに戻るたびにのみ実行されます。ウィンドウがアクティブな場合、毎秒実行されるわけではありません。