我想在JavaScript中运行一个计时器30秒,播放一个哔哔.WAV文件,然后计数10秒并再次发出哔声。我希望重复此操作,直到达到所需的时间或用户介入并单击停止按钮。
这就是我实现它的方式:
function startWorkOut(param) {
if (param === 1) {
setTimeout(playBeep, 30000); //30 second workout
}
else if (param === 0) {
setTimeout(playBeep, 10000); //10 second rest
}
return;
}
function playBeep() {
beep.play(); //already loaded above this snippet
i++; //simple switch for going back and forth between 30 & 10 secs
if (i % 2 === 1) {
startWorkOut(0);
}
else startWorkOut(1);
return;
}
问题是我不知道如何阻止它。因为这两个函数来回互相调用,所以我需要知道如何进行某种手动休息。
答案 0 :(得分:7)
将其分配给变量
var beepTimer = setTimeout(playBeep, 30000); //30 second workout
clearTimeout(beepTimer); // This will clear that timer
答案 1 :(得分:0)
试试这个;
var timerConst;
function startWorkOut(param) {
if (param === 1) {
timerConst = setTimeout(playBeep, 30000); //30 second workout
}
else if (param === 0) {
timerConst = setTimeout(playBeep, 10000); //10 second rest
}
return;
}
function playBeep() {
beep.play(); //already loaded above this snippet
i++; //simple switch for going back and forth between 30 & 10 secs
if (i % 2 === 1) {
startWorkOut(0);
}
else startWorkOut(1);
return;
}
function stop(){
clearTimeout(timerConst);
}
答案 2 :(得分:0)
存储 setTimeout 或 setInterval 方法返回的引用,然后使用window.clearTimeout或window.clearInterval删除这些计时器。例如:
var ref1 = window.setTimeout(function() {your code}, 5000);
var ref2 = window.setInterval(function() {your code}, 5000);
然后使用以下代码删除它们:
window.clearTimeout(ref1);
window.clearInterval(ref2);
希望有所帮助。
答案 3 :(得分:0)
的 jsFiddle Demo
强> 的
“我想在JavaScript中运行一个计时器30秒,播放一个哔哔.WAV文件,然后计数10秒并再次发出哔哔声。我希望重复此操作直到达到所需时间或用户干预并且点击停止按钮。“
为简洁起见,计时器为3秒和1秒
var playing;//variable for timer
function startWorkOut(){
var entry = playing === void 0;//true if playing is undefined
var interval = entry? 3000 : 1000;//first entry is 3s timer, others are 1s
if(!entry)playBeep();//play a beep except when the workout timer is first started
playing = setTimeout(startWorkOut,interval);//play a beep in either 3s or 1s
}
function stopWorkOut(){
clearTimeout(playing);//stops timer
playing = undefined;//restores variable state
}