Question

I have an ajax request that refreshes a page using setInterval every 5 seconds.

Within that ajax request I have another setInterval function to blink a every half second if a condition is true.

What happens is it seems to work fine after the initial ajax call. However, with every 5 second refresh ajax refresh, my blink function timer is halved, effectively doubling the speed.

Any help would be appreciated, thanks!

Here is the code:

$(document).ready(function() {
    var refreshRate = 5000;
    var autoRefresh = setInterval(
      function ()  // Call out to get the time
        {
          $.ajax({
            type: 'GET',
            success: function(data){
                document.getElementById('data').innerHTML=data;

                var blink = setInterval (function () {
                  var blink_cell = $("#blink_div").html();
                  if (blink_cell > 0) {
                    $("#blink_div").toggleClass("blink");
                  } else {
                    $("#blink_div").addClass("invisible");
                  }
                },500);

          } // end success
        });  // end ajax call
     }, refreshRate);// end check
  }); // end ready
Was it helpful?

Solution

Be concerned with the scope of your variables and clear the blink intervall before initiating a new one.

$(document).ready(function() {
    var refreshRate = 5000;
    var blink = -1;
    var autoRefresh = setInterval(
      function ()  // Call out to get the time
      {
          $.ajax({
            type: 'GET',
            success: function(data){
                document.getElementById('data').innerHTML=data;
                if(blink>-1) clearInterval(blink);
                blink = setInterval (function () {
                  var blink_cell = $("#blink_div").html();
                  if (blink_cell > 0) {
                    $("#blink_div").toggleClass("blink");
                  } else {
                    $("#blink_div").addClass("invisible");
                  }
                },500);

          } // end success
        });  // end ajax call
     }, refreshRate);// end check
  }); // end ready

OTHER TIPS

$(document).ready(function () {

  var _url = ''; // Put your URL here.
  var _checkServerTime = 5000;
  var _blinkTime = 500;

  function _blink() {
    // Do something here.
    var condition = true; // Put condition here.
    if (condition) setTimeout(_blink, _blinkTime);
  }

  function _handleData(data) {
    $('#data').html(data);
    _blink();
  }

  function _checkServer() {
    $.get(_url, _handleData);
  }

  setInterval(_checkServer, _checkServerTime);

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top