I referred to Example #2 in the Mozilla docs about setInterval() (https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval?redirectlocale=en-US&redirectslug=DOM%2Fwindow.setInterval#Example_1.3A_Generic) in my JSFiddle but the text color does not alternate between red and blue as expected:
DEMO: http://jsfiddle.net/lpsternotes/JHpt9/
Could it be due to a requirement for jQuery or a markup issue, even though I copied the code exactly as is?
I would also like to clarify: is the reason var nIntervId; is declared as a global variable at the beginning so that it can be accessed by both the changeColor() and stopTextColor() functions?
var nIntervId; //global variable
function changeColor() {
nIntervId = setInterval(flashText, 500);
}
function flashText() {
var oElem = document.getElementById("my_box");
oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}
function stopTextColor() {
clearInterval(nIntervId);
}
In other words, if the code were written like this:
function changeColor() {
var nIntervId = setInterval(flashText, 500);
}
function flashText() {
var oElem = document.getElementById("my_box");
oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}
function stopTextColor() {
clearInterval(nIntervId); //would this lead to an undefined variable??
}