SetTimeout 递归 (Javascript) [英] SetTimeout recursion (Javascript)
问题描述
下面的代码递归播放音频元素并跟踪文本的迭代,这两者都通过清除超时的按钮停止.
The code below recursively plays an audio element and tracks iterations to text, both of which are stopped via a button that clears their timeouts.
如果 playTimeout 被分配给外部函数 nextThing
,当点击停止按钮时,音频将在文本迭代停止后再次播放.然而,在 playTimeout 的注释(内部)版本中,音频会立即停止.
If playTimeout is assigned to external function nextThing
, when the stop button is clicked the audio will play once more after the text iterations stop. However in the commented (internal) version of playTimeout, the audio stops right away.
问题:a) 为什么会发生这种情况?和 b) 我如何正确地表达这一点,以便迭代和音频一起移动?
Questions: a) why is this happening? and b) how can I properly phrase this so iterations and audio move together?
function nextThing(millis,pitch){
setTimeout(playTone,millis,pitch);
};
function timedCount(millis){
document.getElementById('txt').value=iteration;
playTimeout=nextThing(millis,"C3");
// playTimeout=setTimeout(playTone,millis,"C3")
doRecursion=setTimeout(function(){timedCount(millis)},millis);
iteration++;
console.log("made it");
}
推荐答案
你的 nextThing
函数没有返回任何东西,定时器 ID 被忽略,它会分配 undefined
playTimeout
.
Your nextThing
function didn't return anything, the timer id is ignored and it would assign undefined
to playTimeout
.
function nextThing(millis, pitch) {
return setTimeout(playTone, millis, pitch);
// ^^^^^^
}
这篇关于SetTimeout 递归 (Javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!