So I have a timer function that checks for an item (if it's not found for an extra 5 seconds once every 200ms for 5000 ms) and I am looking to try and condense this function. It gets the job done currently, it just seems like I'm using an excess of code to do it. Here's what I've got:
var timeToCheck = true;
setTimeout(function() {
timeToCheck = false;
}, 5000);
var check = {
init: function() {
check.checkAgain();
},
checkAgain: function() {
if (timeToCheck) {
if (currentModules[name]) {
//by some act of god, this module exists now
} else {
//still doesn't exists
setTimeout(check.checkAgain, 200);
}
} else {
//doesn't exist after 5 seconds
$log.error("Requested module (" + name + ") could not be found at this time.");
}
}
};
check.init();
I'm wondering if I could get any pointers (or help) in making this a little more elegant and less code if possible.
I think it would be cleaner to call check
recursively. You should avoid having two separate setTimeouts
(it could end up netting you unexpected results, especially in a scenario where the timeouts
are interdependent) - read up on the event loop if you are not familiar with how it works.
var TIMEOUT_DUR = 200;
var MAX = 5000;
var accum = 0;
function check () {
if ( accum >= MAX ) {
$log.error( '...' );
return;
}
setTimeout( function () {
if ( currentModules[ name ] ) {
// do things
return;
}
accum += TIMEOUT_DUR;
check();
}, TIMEOUT_DUR );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.