I have had this issue before on another project. When I include my variables in a function with local scope, the function is able to run. When I put the variable outside of function with global scope, the function does not interpret the variables and does not run. I've tried passing the global variables into my functions and it does not run.
This example is a snippet of a countdown timer I was working on:
LOCAL SCOPE (FUNCTION RUNS) http://jsbin.com/leyicubegu/2/edit
function addTime() {
var userTime = timeInput.value;
var timeString = userTime.toString();
var timeArray = timeString.split("");
var hundrethsValue = timeArray[6].concat(timeArray[7]);
var secondsValue = timeArray[3].concat(timeArray[4]);
var minutesValue = timeArray[0].concat(timeArray[1]);
var hundreths = hundrethsValue;
var seconds = secondsValue;
var minutes = minutesValue;
document.getElementById("time").innerHTML = minutes + ":" + seconds + ":" + hundreths;
}
GLOBAL SCOPE (FUNCTION DOES NOT RUN) http://jsbin.com/fuxexajozu/2/edit
var userTime = timeInput.value;
var timeString = userTime.toString();
var timeArray = timeString.split("");
var hundrethsValue = timeArray[6].concat( timeArray[7]);
var secondsValue = timeArray[3].concat(timeArray[4]);
var minutesValue = timeArray[0].concat(timeArray[1]);
var hundreths = hundrethsValue;
var seconds = secondsValue;
var minutes = minutesValue;
function addTime() {
document.getElementById("time").innerHTML = minutes + ":" + seconds + ":" + hundreths;
}
PASSING VARIABLES TO FUNCTION (GLOBAL SCOPE) - (FUNCTION DOES NOT RUN)
var userTime = timeInput.value;
var timeString = userTime.toString();
var timeArray = timeString.split("");
var hundrethsValue = timeArray[6].concat( timeArray[7]);
var secondsValue = timeArray[3].concat(timeArray[4]);
var minutesValue = timeArray[0].concat(timeArray[1]);
var hundreths = hundrethsValue;
var seconds = secondsValue;
var minutes = minutesValue;
function addTime(minutes, seconds, hundreths) {
document.getElementById("time").innerHTML = minutes + ":" + seconds + ":" + hundreths;
}
*note: the running function only runs in jsbin, not jsfiddle
I can't identify why the the variables only run with a local scope. I would like them to run with global scope so that I can use them in multiple functions. Please provide any input. I am new to this so my knowledge of scopes is limited.
HTML (if needed)
<input id="timeInput" name="timeInput" type="text " length="20">
<h1><div id="time">00:00:00</div></h1>
<div id="result"></div>
<button onclick=addTime(); >Submit</button>
<button id="start" onclick = startClock();>Start</button>
<button id="stop" onclick="stopTimer();">Stop</button>
<button id="clear" onclick="resetTimer();">Reset</button>