cybrain
cybrain

Reputation: 61

How to make setInterval run when browser tab is on focus?

I have created an Interval that runs on every 2 seconds, when the page loads. Now, when I move to other page, the interval is cleared (Please check the code). Now what I want is when I move to the same tab again, the interval should start again.

One thing I tried was that I wrote this whole code inside $(window).focus(//CODE) but the problem is that it doesn't run when the page is initially opened in any browser's tab.

How can solve this issue?

Here's my code:

var zzz= setInterval(anewFunc, 2000);
function anewFunc(){
  $(document).ready(function(){

    var chatattr=$(".chatwindow").css("visibility");
    var chattitle=$("#hideid").text();
    if(chatattr=="visible"){
      $.ajax({
        url: 'seen1.php',
        type: 'post',
        data: "ctitle="+chattitle,
        success: function(result9){
        },
        error: function(){
        }
      });

    }
    $(window).blur(function(){
      $.ajax({
        url: 'session.php',
        type: 'post',
        success: function(result10){
          //  alert(result10);
        },
        error: function(){
        }
      });
      clearInterval(zzz);
    });
  });
}

Upvotes: 3

Views: 862

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

One thing I tried was that I wrote this whole code inside $(window).focus(//CODE) but the problem is that it doesn't run when the page is initially opened in any browser's tab.

Okay, the problem here is, the setInterval() doesn't execute at 0 seconds. It starts from 2 seconds only. So you need to make a small change:

  1. Have the function separately.
  2. Inside the ready event, start the timer, as well as run the function for the first time.
  3. Remove the event handlers from the interval, or use just .one() to assign only once. You are repeatedly adding to the .blur() event of window.

Corrected Code:

function anewFunc() {

  var chatattr = $(".chatwindow").css("visibility");
  var chattitle = $("#hideid").text();
  if (chatattr == "visible") {
    $.ajax({
      url: 'seen1.php',
      type: 'post',
      data: "ctitle=" + chattitle,
      success: function(result9) {},
      error: function() {}
    });
  }
  $(window).one("blur", function() {
    $.ajax({
      url: 'session.php',
      type: 'post',
      success: function(result10) {
        //  alert(result10);
      },
      error: function() {}
    });
    clearInterval(zzz);
  });
}

$(document).ready(function() {
  var zzz = setInterval(anewFunc, 2000);
  anewFunc();
});

Now what I want is when I move to the same tab again, the interval should start again.

You haven't started the setInterval() again.

$(document).ready(function () {
  $(window).one("focus", function() {
    var zzz = setInterval(anewFunc, 2000);
  });
});

Upvotes: 2

Related Questions