1

I wrote a program which generates notes and plays them in sequence. However, I have one main timer(here, myTimer) which runs a function which calls another timer(timerForIndividualNotes). After myTimer runs once, timerForIndividualNotes runs once and just stops after one round. Any reason why?

This is the first function

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);
}
}

This is the function being called

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 Answers1

0

You only call runMusicGenerator once when you pass it to setInterval. setInterval expects an callback which you dont supply.

Try:

myTimer = setInterval(function() {
  runMusicGenerator(intervalTime);
},intervalTime);
Code Spirit
  • 3,992
  • 4
  • 23
  • 34
  • Haven't I shown setInterval the callback by passing runMusicGenerator as the first argument? Why doesn't it work by just stating the function instead of writing function(){runMusicGenerator(intervalTime); instead of setInterval(runMusicGenerator(intervalTime)) – AnikethSuresh Nov 06 '18 at 09:06
  • Because `runMusicGenerator(intervalTime) ` **calls** the function, and you want to **pass** it. `runMusicGenerator(intervalTime)` would work if you return a `function` from it. – Code Spirit Nov 06 '18 at 10:30