我正在开发一个需要多个 JavaScript 元素相互同步的音乐程序。我一直在使用 setInterval
,最初效果非常好。然而,随着时间的推移,元素逐渐变得不同步,这在音乐节目中是很糟糕的。
我在网上看到 setTimeout
更准确,你可以用某种方式让 setTimeout
循环。但是,我还没有找到一个通用版本来说明这是如何实现的。
基本上我有这样一些功能:
//drums
setInterval(function {
//code for the drums playing goes here
}, 8000);
//chords
setInterval(function {
//code for the chords playing goes here
}, 1000);
//bass
setInterval(function {
//code for the bass playing goes here
}, 500);
它最初运行得非常好,但在大约一分钟的过程中,声音变得明显不同步,因为我读到过 setInterval
发生的情况。我读到 setTimeout
可以更加一致地准确。
谁能告诉我一个使用 setTimeout
无限循环某些内容的基本示例?或者,如果有办法通过 setInterval
或其他函数实现更多同步结果,请告诉我。
最佳答案
您可以使用递归创建一个setTimeout
循环:
function timeout() {
setTimeout(function () {
// Do Something Here
// Then recall the parent function to
// create a recursive loop.
timeout();
}, 1000);
}
setInterval()
和setTimeout()
的问题在于无法保证您的代码会在指定时间内运行。通过使用 setTimeout()
并递归调用它,您可以确保在下一次代码迭代开始之前完成超时内的所有先前操作。
关于javascript - 如何使 `setInterval` 表现得更同步,或者如何使用 `setTimeout` 代替?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22154129/