I have a function, which retrieves data from the database and passes it to callback. For optimization purposes I want this data to be updated at most once per 60 seconds. My closure function looks like:
function delayedUpdate(fn, delay, callback) {
var nextCall = Date.now();
var data = false;
(function () {
if (nextCall <= Date.now()) {
nextCall = Date.now() + delay;
fn(function (err, res) {
data = err ? false : res;
callback(err, data);
});
} else {
callback(null, data);
}
})();
}
I noticed that when I "construct" this function in my desired funtion, which is called very often I'm basically creating a closure in loop, so it has no chance to work properly:
function update()
{
delayedUpdate(server.getDbData, 60000, function (err, data) {
someDataToRender = data;
});
}
Wrapping delayedUpdate
in other function and assigning to variable doesn't work aswell. How can I accomplish my goal? I know this might be dumb question, but I'm still learning.