Skip to content

Commit

Permalink
Merge pull request #6 from sjwood25890/master
Browse files Browse the repository at this point in the history
Rescheduling cache checks using deferred callbacks instead of intervals
  • Loading branch information
johnpbloch committed Apr 30, 2015
2 parents 07da52f + 627d5a8 commit 76ffcdb
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions live-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
function Live_Cache_Obj() {
var self = this,
ajaxurl = LC.ajaxurl, // ajaxurl and auto_updates values originally set by localize script
values = [],
values = {
refresh_rate: 60 // Initialize to 60s here too
},
callbacks = [],
timeStamp = 1,
errs = 0,
Expand Down Expand Up @@ -40,6 +42,19 @@
self.check();
}, 10000);

this.reschedule = function() {
// If we've had less than three errors, continue to reschedule, otherwise just kill the live cache check
if (errs < 3) {
// Clear any existing timeout
clearTimeout(self.timer);

// Set a new timeout, for 60s (or longer) in the future
self.timer = setTimeout(function() {
self.check();
}, 1000 * Math.max(60, getRefreshRate(values.refresh_rate)));
}
};

// to customize what happens when a value is updated, set a callback for that key
this.setCallback = function (key, callback) {
if (undefined === callbacks[key]) {
Expand Down Expand Up @@ -91,9 +106,11 @@
},
dataType: "json",
error : function () {
callbacks['refresh_rate'].fire('refresh_rate', getRefreshRate(60) * ++errs);
// On an error, increase the refresh rate a little
values.refresh_rate = getRefreshRate(60) * ++errs;
}
});
})
.always(self.reschedule);
}
};
}
Expand All @@ -104,7 +121,7 @@

function liveCacheCallbackGenerator(lc) {
return function (k, v) {
$(lc.auto_updates[k]).html(v);
$(lc.auto_updates[k]).text(v);
};
}

Expand All @@ -117,15 +134,4 @@
}
}


/*
* Use our own system - reset our timer if the refresh rate has been updated
* Also a handy usage demo
*/
liveCache.setCallback('refresh_rate', function (key, value) {
clearTimeout(liveCache.timer);
liveCache.timer = setTimeout(function () {
liveCache.check();
}, value * 1000);
});
}(this, this.jQuery, this.Live_Cache));

0 comments on commit 76ffcdb

Please sign in to comment.