Javascript,setTimeout循环? [英] Javascript, setTimeout loops?

查看:120
本文介绍了Javascript,setTimeout循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在制作一个音乐程序,需要多个javascript元素与另一个同步。我一直在使用setInterval,它最初工作得非常好,但是随着时间的推移,元素会逐渐变得不同步,而音乐程序则很糟糕。

So I am working on a music program that requires multiple javascript elements to be in sync with another. I've been using setInterval which works really well initially however over time the elements gradually become out of sync which with a music program is bad.

我在网上看过setTimeout更准确,你可以以某种方式使用setTimeout循环但是我没有找到一个通用版本来说明这是如何可行的。有人可以向我展示一个使用setTimeout无限循环的基本示例。

I've read online that setTimeout is more accurate, and you can have setTimeout loops somehow however I have not found a generic version that illustrates how this is possible. Could someone just show me a basic example of using setTimeout to loop something indefinitely.

谢谢。或者,如果有办法通过setInterval甚至其他函数获得更多同步结果,请告诉我。

Thank you. Alternatively, if there is a way to achieve more synchronous results with setInterval or even another function, please let me know.

编辑:

基本上我有一些类似的函数:

Basically I have some functions like such:

//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可以更加一致地准确。

It works super well initially but over the course of about a minute, the sounds become noticeably out of sync as I've read happens with setInterval, I've read that setTimeout can be more consistently accurate.

推荐答案

你可以创建一个 setTimeout 使用递归循环:

You can create a setTimeout loop using recursion:

function timeout() {
    setTimeout(function () {
        // Do Something Here
        // Then recall the parent function to
        // create a recursive loop.
        timeout();
    }, 1000);
}

setInterval()的问题 setTimeout()是无法保证您的代码将在指定时间内运行。通过使用 setTimeout()并递归调用它,您可以确保在下一次代码迭代开始之前,超时内的所有先前操作都已完成。

The problem with setInterval() and setTimeout() is that there is no guarantee your code will run in the specified time. By using setTimeout() and calling it recursively, you're ensuring that all previous operations inside the timeout are complete before the next iteration of the code begins.

这篇关于Javascript,setTimeout循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆