0

カウントダウンは、ウィンドウがアクティブなときだけカウントダウンし、ウィンドウがアクティブでなくなるたびに停止するようにしようとしています。

私はこのプラグインを使用しています: 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);は、別のウィンドウ/タブに移動してから最初のウィンドウに戻るたびにのみ実行されます。ウィンドウがアクティブな場合、毎秒実行されるわけではありません。

4

1 に答える 1

0

私が間違っていなければ、setTimout()は 1 回だけ実行されます。あなたが望むのはsetInterval()で、 clearInterval() 関数でクリアされるまで、指定した間隔で何度も関数を呼び出します。

私が取るアプローチは、内部残り時間、間隔プロパティ、および一時停止、再開、カウントダウン、および終了メソッドを使用して、カウントダウン オブジェクトを作成することです。

function Countdown( time ) {

 var self = this; // self reference

 var time = parseInt( time ) || 10;  // default to 10 s

 var timer = false;

 this.countDown = function() {    
  if ( --time < 1 ) {
   self.finish();
  }
  else {
   // code to update countdown display on page
  }
  return this;
 }

 this.finish = function() {
  this.pause();
  // the code you want to execute when time reaches 0
  return this;
 }

 this.resume = function() {
  if ( !timer ) {
   if ( time > 0 ) {
    timer = setInterval( function() {
     self.countDown();
    }, 1000 );
   }
   else {
    this.finish();
   }
  }
  return this;
 }

 this.pause = function() {
  if ( timer ) {
   clearInterval( timer );
   timer = false;
  }
  return this;
 }

}

したがって、Countdown オブジェクトを作成し、pause メソッドと resume メソッドをページの表示変更イベントにバインドするだけです。

カウントダウンを開始するかどうかを決定するために、Countdown オブジェクトが作成されたときにページの表示ステータスを確認することもできます。

于 2014-05-19T13:38:12.487 に答える