我们有一个AJAX系统设置,可以使用Chrome浏览器在不同事件时检查未读消息:
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'});
});
}
我们想设置一个间隔的变量(例如每5分钟),仅每5分钟发送一次Ajax调用,或者可以将任何变量设置为。
有人可以帮助我们确定在哪里添加此行为?我以为Pollinterval会处理它,但没有。
我将在XHR对象中添加一个onreadystatechange函数,以便在完成后再次调用该函数。在您的JHR声明中:
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
timerId && clearTimeout(timerId);
timerId = setTimeout(startRequest, pollInterval);
}
}
如果要使用setInterval,则应在启动另一个XHR对象(通过其Readystate属性)中检查以前的XHR对象。
尝试更改代码以使用clearInterval
:
var pollInterval = 1*60*60; // 60 min
var timerId;
function startRequest() {
updateBadge();
timerId = window.setInterval(startRequest, pollInterval);
}
function stopRequest() {
window.clearInterval(timerId);
}
更多关于setInterval
:
http://www.w3schools.com/jsref/met_win_clearinterval.asp
https://developer.mozilla.org/en-us/docs/web/api/window.clearinterval
setInterval以及如何使用clearinterval