function muteEvent(id) {
var button = "#muteBox".concat(id.charAt(id.length - 1));
var value = $(button).css("background-color");
var slider = "#sliderKnob".concat(id.charAt(id.length - 1));
var animation = function() {
if ($(slider).css("background-color") == 'rgb(0, 128, 0)') {
$(slider).css("background-color", "red")
} else {
$(slider).css("background-color", "green")
}
}
if (value == 'rgb(128, 128, 128)') {
$(button).css("background-color", "red");
var timer = setInterval(animation, 1500)
} else {
alert("here");
clearInterval(timer);
$(button).css("background-color", "#808080");
}
}
答案 0 :(得分:1)
clearInterval
获取标识符(从setInterval
返回)以停止重复计时器。在您拨打clearInterval
时,将此标识符保存在仍在范围内的位置 - 注意它将是muteEvent
单独调用代码的方式。
var intervalId = null;
function muteEvent(id) {
var button = "#muteBox".concat(id.charAt(id.length - 1));
var value = $(button).css("background-color");
var slider = "#sliderKnob".concat(id.charAt(id.length - 1));
var animation = function() {
if ($(slider).css("background-color") == 'rgb(0, 128, 0)') {
$(slider).css("background-color", "red")
} else {
$(slider).css("background-color", "green")
}
}
if (value == 'rgb(128, 128, 128)') {
$(button).css("background-color", "red");
intervalId = setInterval(animation, 1500)
} else {
alert("here");
clearInterval(intervalId);
$(button).css("background-color", "#808080");
}
}
$("#muteBox2").click(muteEvent.bind(null, "2"));
#muteBox2 {
background-color: rgb(128,128,128);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="muteBox2">Mute</div>
<div id="sliderKnob2">Slider</div>