Как я могу использовать clearInterval() или какой-либо другой метод, чтобы сделать мой сценарий затухания фона в JavaScript, который использует setInterval(), остановить?
У меня есть вложенная функция замыкания, которая зацикливает и затухает мой цвет фона на основе назначений в массиве. На кнопке с методом onclick "stopFadeColors()", которую я запустил, как я могу на самом деле остановить запуск скрипта, нажав вторую кнопку?
<style>
.black {
-moz-transition: all .2s ease-in;
-o-transition: all .2s ease-in;
-webkit-transition: all .2s ease-in;
transition: all .2s ease-in;
background: #000;
}
.white {
-moz-transition: all .2s ease-in;
-o-transition: all .2s ease-in;
-webkit-transition: all .2s ease-in;
transition: all .2s ease-in;
background: #fff;
}
</style>
<script>
//make the element start blinking at a rate of once per second.
function fadeColors(target) {
var elem = document.body; //assign the object to a shorter named object
var toggleColor = ["black", "white"]; // setup color list, it can be more than two
var counter = 0; //outer counter
var nextColor; //outerClass
function changeBackgroundColor() {
console.log(counter); // output count
counter = (counter + 1) % toggleColor.length; //modulus of counter divided by counter length
nextColor = toggleColor[counter]; //update the class
elem.className = nextColor; //assign the class
}
setInterval(changeBackgroundColor, 1000); //call our function
}
</script>
<button onclick="fadeColors()">Fade Background</button>
<!-- how can i make this next button call a new or existing method and pause the script with clearInterval() or some other way? --//>
<button onclick="stopFadeColors()">Stop Fade Background</button>
1 ответ
Решение
Вы должны назначить свой setInterval()
функция к переменной:
function fadeColors(target) {
var elem = document.body; //assign the object to a shorter named object
var toggleColor = ["black", "white"]; // setup color list, it can be more than two
var counter = 0; //outer counter
var nextColor; //outerClass
function changeBackgroundColor() {
console.log(counter); // output count
counter = (counter + 1) % toggleColor.length; //modulus of counter divided by counter length
nextColor = toggleColor[counter]; //update the class
elem.className = nextColor; //assign the class
}
document['intervalTemp'] = setInterval(changeBackgroundColor, 1000); //call our function
}
HTML:
<button onclick="fadeColors();">Fade Background</button>
Другие кнопки нажмите, чтобы остановить:
<button onclick="clearInterval(document.intervalTemp);">Stop Fade Background</button>