I am trying to get my head around the various techniques that can be used to avoid the use of global variables in JavaScript.
Consider the following code, that performs a redirect to a URL after a countdown timer:
var _redirectTimer;
function startRedirectTimer() {
clearTimeout(_redirectTimer);
var redirectTimer = function(timeLeft) {
if(timeLeft == 0) {
// redirect to application path
var redirectURL = window.location.protocol+"//"+window.location.host + "/" + location.pathname.split("/")[1];
window.location.replace(redirectURL);
return;
} else {
timeLeft--;
_redirectTimer = setTimeout(function () {redirectTimer(timeLeft)}, 1000);
}
}
redirectTimer(60);
}
My client code only ever calls startRedirectTimer(). However, _redirectTimer is a global variable that I'd rather not expose.
Ideally, I'd like this variable to be a "state" variable within startRedirectTimer(), similar to how you'd have a private method in a singleton java class.
Can someone advise on how I can achieve this?
Thanks