0

I am trying to do so my countdown will only count down whenever the window is active, and then stop whenever the window is not active anymore.

I'm using this plugin: 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);

        }


    }

How is it possible to do so the jquery visibility API will run not just once, but each second when the page is active - and then trigger another function when the page isn't active?

At this current state, this: setTimeout("runCounter()",1000); will only run whenever I go to another window/tab and then go back to the first window. It will not run each second when the window is active.

4

1 回答 1

0

如果我没记错的话,setTimout()只运行一次。我相信您想要的是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 回答