短暂停顿 - 我使用wad JavaScript library创建随机音调生成器。我正试图让发电机“滑动”。间距之间,如下伪码:
如果我从if语句中删除for循环并从变量手动设置其起始音高,它将按预期运行。
我做错了什么?我的if语句有问题吗?用我的for循环?
有问题的代码是:
// play the first pitch
function playFirst() {
if(!stopped){
window.randomNum = Math.round(Math.random()*200 + 100);
console.log("randomnum is now "+ randomNum);
}
playRandom();
}
// play and loop subsequent pitches
function playRandom(){
if(!stopped){
var randomNext = Math.round(Math.random()*200 + 100);
console.log("randomNext is now " + randomNext);
var howManyCents = randomNum - randomNext;
console.log(howManyCents + " cents");
// ascending note slide condition
if (randomNum < randomNext) {
console.log("randomnum is less!");
var inbetweenNum = randomNum + 1;
// for loop - the part with the problem!
for (var i = 0; i < howManyCents; i++) {
inbetweenNum = randomNum + i;
console.log("inbetween number is " + inbetweenNum);
inbetween.play({ pitch : inbetweenNum });
console.log("played inbetween up");
}
// descending note slide condition
} else {
console.log("randomnum is more!");
var inbetweenNum = randomNum - 1;
// another problematic for loop
for (var i = 0; i > howManyCents; i--) {
inbetweenNum = randomNum - i;
console.log("inbetween number is " + inbetweenNum);
inbetween.play({ pitch : inbetweenNum });
console.log("played inbetween down");
}
}
// actually play the note
bell.play({ pitch : randomNext, wait: 0 });
console.log("played randomnext" + randomNext);
// reassign the new note as the current note
randomNum = randomNext;
console.log("randomnum is now" + randomNum);
setTimeout(playRandom,1500); // and loop it
}
}
我已经制作了完整程序here的JSFiddle。
非常感谢任何帮助!
答案 0 :(得分:1)
该块的条件是randomNum < randomNext
,但howManyCents
是randomNum - randomNext
,在这种情况下将为负值。循环条件,然后 - i < howManyCents
,i
从0开始,将永远不会成立。
您可以使用i < -howManyCents
,或将Math.abs(randomNum - randomNext)
分配给howManyCents
,i > howManyCents
和i--
。