Question

We have an ajax system setup to check for unread messages during different events using a chrome browser:

var JHR = function ( method, url, data, fun ) {
  var xhr = new XMLHttpRequest();
  xhr.responseJSON = null;

  // xhr.open( 'POST', url );
  xhr.open(method, url, true);
  xhr.setRequestHeader("Authorization", "Basic " + data.userAuth);
  xhr.setRequestHeader( 'Content-Type', 'application/json' );

  xhr.addEventListener( 'load',  function () {
    //my old man once told me "Zirak, sometimes, you must face the dangers
    // of life head on". he then threw me in a shark tank. but I'm sure it
    // applies here too.
    //...I was only 7
    xhr.responseJSON = JSON.parse( xhr.responseText );

    if (fun) fun( xhr.responseJSON, xhr );
  });

  xhr.send( JSON.stringify(data) );

  return xhr;
};


var pollInterval = 1*60*60; // 60 min
var timerId;

function startRequest() {
    updateBadge();
    timerId = window.setTimeout(startRequest, pollInterval);
}
function stopRequest() {
    window.clearTimeout(timerId);
}

function getUnreadCount(onSuccess, onError) {
  chrome.storage.sync.get("userAuth", function(data) {
    var response = JHR("GET", "https://api.rss.com/v2/unread_entries.json", {userAuth: data.userAuth}); 
    console.log(response);
  }); 
}

function updateBadge() {
    // Callbacks for onSuccess, and onError
    getUnreadCount(function(data) {
        chrome.browserAction.setBadgeText({text:data.unreadItems});
    }, function(data){
        chrome.browserAction.setBadgeText({text:'error'});
    });
}

We would like to set a variable for an interval (every 5 minutes for example) and only send the ajax call out every 5 minutes or whatever the variable might be set to.

Can someone help us determine where to add this behavior? I thought the pollInterval would handle it but it doesn't.

Was it helpful?

Solution

I would add a onreadystatechange function to your xhr object to just call the function again upon completion. Inside your JHR declaration:

xhr.onreadystatechange = function() {
  if(xhr.readyState == 4) {
    timerId && clearTimeout(timerId);
    timerId = setTimeout(startRequest, pollInterval);
  }
}

If you were to use setInterval instead you should check the previous xhr object for completion (via its readyState property) before firing another one.

OTHER TIPS

Try changing your code to use clearInterval:

var pollInterval = 1*60*60; // 60 min
var timerId;

function startRequest() {
    updateBadge();
    timerId = window.setInterval(startRequest, pollInterval);
}

function stopRequest() {
    window.clearInterval(timerId);
}

More about setInterval:

http://www.w3schools.com/jsref/met_win_clearinterval.asp

https://developer.mozilla.org/en-US/docs/Web/API/Window.clearInterval

setInterval and how to use clearInterval

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