1

我想在 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;     

}

问题是我不知道如何阻止它。因为这两个函数来回调用对方,我需要知道如何进行某种手动中断。

4

4 回答 4

7

将其分配给变量

 var beepTimer = setTimeout(playBeep, 30000); //30 second workout

clearTimeout(beepTimer);  // This will clear that timer
于 2013-05-16T19:10:26.990 回答
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);
   }
于 2013-05-16T19:11:56.083 回答
0

存储setTimeoutsetInterval方法返回的引用,然后使用 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);

希望它有所帮助。

于 2013-05-16T19:13:56.320 回答
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
}
于 2013-05-16T19:15:09.263 回答