I decided to contain this code into an object to separate it out from the areas it will be applied. Any advice here is really appreciated:
appConfig.loadElement and appConfig.cerrorElement are these HTML elements:
<div id="loading" style="display:none;">Loading...</div>
<div id="cerror" style="display:none;">Connection Error.</div>
var loadingTimeoutInstance = null, cerrorTimeoutInstance = null,
requestObj = {
reset: function() {
$(appConfig.loadElement).hide();
$(appConfig.cerrorElement).hide();
clearTimeout(loadingTimeoutInstance);
clearTimeout(cerrorTimeoutInstance);
},
initiate: function() {
loadingTimeoutInstance = setTimeout(requestObj.timeout, appConfig.loadingDelayMS);
},
timeout: function () {
clearTimeout(loadingTimeoutInstance);
$(appConfig.loadElement).show();
cerrorTimeoutInstance = setTimeout(requestObj.cerror, appConfig.cerrorDelayMS);
},
cerror: function () {
clearTimeout(cerrorTimeoutInstance);
$(appConfig.loadElement).hide();
$(appConfig.cerrorElement).show();
}
}
An implementation is like so:
When an asynchronous request is made:
requestObj.reset();
requestObj.initiate();
After the response is returned:
requestObj.reset();
The problems I have identified are mainly in requestObj.reset():
– Why hide elements if they are already hidden?
– Can’t clear the timeout vars (loadingTimeoutInstance and cerrorTimeoutInstance) if they are not set as timeouts yet – this causes it not to work.
You don’t actually need to check if it’s of a certain type… just that it is.
if(cerrorTimeoutInstance) clearTimeout(cerrorTimeoutInstance);