setInterval() に関する Mozilla ドキュメントにある例 #2 をコピーしました ( https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval?redirectlocale=en-US&redirectslug=DOM%2Fwindow. setInterval#Example_1.3A_Generic ) しかし、私の JSFiddle ではテキストの色が赤と青の間で交互になりません:
デモ: http://jsfiddle.net/lpsternotes/JHpt9/
jQuery が必要なためでも、マークアップのためでもありません。私はそれを正確にコピーしました。
また、明確化のためにお願いしたいと思いました。理由は var nIntervId; です。上部のグローバル変数として定義されているのは、changeColor() 関数と stopTextColor() 関数の両方で使用できるようにするためですよね?
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);
}
つまり、コードが次のようになっているとします。
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); //undefined??
}