计时器停止运行而未调用clearInterval

时间:2018-11-06 08:23:43

标签: javascript timer

我编写了一个程序,该程序生成音符并按顺序播放它们。 然而, 我有一个主计时器(这里是myTimer),它运行一个调用另一个计时器(timerForIndividualNotes)的函数。 myTimer运行一次后,timerForIndividualNotes运行一次,并在下一轮后停止。有什么原因吗?

这是第一个功能

function runTimer(){
var button = document.getElementById("submitButton"); 
if(button.innerHTML === "Shoot!"){
    var intervalTime = document.getElementById("intervalTime");
    intervalTime = intervalTime.value*1000;
    myTimer = setInterval(runMusicGenerator(intervalTime),intervalTime); // This calls the second function with another timer
    let otherTimer = setInterval(function(){
        console.log("Just testing");
    },1000);
    console.log("Interval ID->"+ myTimer);
    button.style.backgroundColor = "firebrick";
    button.innerHTML = "Stop!";
}
else{
    button.style.backgroundColor = "#28a745";
    button.innerHTML = "Shoot!"
    clearInterval(myTimer);
}
}

这是被调用的函数

function runMusicGenerator(totalIntervalTime){
var inputNum = document.getElementById("inputNum");
var instrument = document.getElementById("selector").value;
var placeToDisplayNotes = document.getElementById("notesItself");
numOfNotes = inputNum.value;

var notes = 
["A","A#",
"B",
"C","C#",
"D","D#",
"E",
"F","F#",
"G","G#"];

var notesOnScreen=[];
var randomnumber;
for (var i=0;i<numOfNotes;i++){
    randomnumber = Math.floor(Math.random() * 12);
    notesOnScreen.push(notes[randomnumber]);
}
console.log(notesOnScreen);
instrumentPlaying = Synth.createInstrument(instrument);
console.log(timeForEachNote);
var i=0,timeForEachNote = totalIntervalTime/notesOnScreen.length;
timerForIndividualNotes = setInterval(function(){ // After executing this once, the timers just stop
    instrumentPlaying.play(notesOnScreen[i],4,2);
    if (i++ >= notesOnScreen.length - 1)
      clearInterval(timerForIndividualNotes);
    }, timeForEachNote);
placeToDisplayNotes.innerHTML = notesOnScreen.join(" ");
}

1 个答案:

答案 0 :(得分:0)

runMusicGenerator传递给setInterval时,您只会调用一次。 setInterval期望您不提供回调。

尝试:

myTimer = setInterval(function() {
  runMusicGenerator(intervalTime);
},intervalTime);