【发布时间】:2015-05-17 06:38:14
【问题描述】:
我有一个程序,当您单击一个按钮时,会循环播放一系列 5 种灯光和声音(基本上,表格中的某些单元格的背景颜色会按顺序改变)。我有另一个按钮“取消”可以取消它。但是,当您单击取消时,它仍然会完成当前循环。理想情况下,我希望它停止中间循环并将所有内容重置为开始(或结束)时的状态。
这是我的 javaScript..
$(document).ready(function() {
var note1 = new Audio("audio/1.wav");
var note2 = new Audio("audio/2.wav");
var note3 = new Audio("audio/3.wav");
var note4 = new Audio("audio/4.wav");
var note5 = new Audio("audio/5.wav");
var isPlaying = false;
var speed = 500;
var buttonPressed = false;
var interval;
$("#button1").click(function(){
if (!buttonPressed) {
noteLoop();
clearInterval(interval);
interval = setInterval(noteLoop, 5000);
$("#button1").text("MAKING CONTACT");
};
$("#button2").click(function() {
clearInterval(interval);
$("#button1").text("CLICK TO MAKE CONTACT");
buttonPressed = false;
$.finish();
})
});
var noteLoop = function() {
if (!isPlaying){
playNotes();
};
}
var playNotes = function() {
setTimeout(play1, speed);
setTimeout(play2, speed * 2);
setTimeout(play3, speed * 3);
setTimeout(play4, speed * 4.6);
setTimeout(play5, speed * 6.2);
setTimeout(function(){
resetNotes();
isPlaying = false;
}, speed * 9);
};
var play1 = function() {
isPlaying = true;
$("table tr:nth-child(2) td:nth-child(2)").addClass("yellow");
$("table tr:nth-child(2) td:nth-child(2)").hide();
$("table tr:nth-child(2) td:nth-child(2)").fadeIn('fast');
note1.play();
};
var play2 = function() {
$("table tr:nth-child(2) td:nth-child(2)").removeClass("yellow");
$("table tr:nth-child(3) td:nth-child(3)").addClass("green");
$("table tr:nth-child(3) td:nth-child(3)").hide();
$("table tr:nth-child(3) td:nth-child(3)").fadeIn('fast');
note2.play();
};
var play3 = function() {
$("table tr:nth-child(3) td:nth-child(3)").removeClass("green");
$("table tr:nth-child(3) td:nth-child(1)").addClass("blue");
$("table tr:nth-child(3) td:nth-child(1)").hide();
$("table tr:nth-child(3) td:nth-child(1)").fadeIn('fast');
note3.play();
};
var play4 = function() {
$("table tr:nth-child(3) td:nth-child(1)").removeClass("blue");
$("table tr:nth-child(1) td:nth-child(4)").addClass("white");
$("table tr:nth-child(1) td:nth-child(4)").hide();
$("table tr:nth-child(1) td:nth-child(4)").fadeIn('fast');
note4.play();
};
var play5 = function() {
$("table tr:nth-child(1) td:nth-child(4)").removeClass("white");
$("table tr:nth-child(4) td:nth-child(2)").addClass("orange");
$("table tr:nth-child(4) td:nth-child(2)").hide();
$("table tr:nth-child(4) td:nth-child(2)").fadeIn('fast');
note5.play();
};
var resetNotes = function() {
$("table tr:nth-child(4) td:nth-child(2)").removeClass("orange");
};
});
我也知道我可能以完全错误的方式处理这件事,我想做的事情甚至可能都不可能。我还希望它每次循环时都变得越来越快,但我想不出任何方法来实现这一点:(
感谢您的帮助。
【问题讨论】:
-
根据您的代码(如果您正在使用音频/视频),您可以将名为“timeupdate”的事件侦听器添加到音频元素,并在其处理程序内部检查是否有任何取消请求,如果重新启动循环..如果不清楚给你举个例子,请告诉我。
-
对不起,我对此还是很陌生,所以如果你能举个例子就好了:)
标签: javascript jquery function settimeout setinterval