如何使setInterval表现得更加同步,或者如何使用setTimeout呢? [英] How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

查看:256
本文介绍了如何使setInterval表现得更加同步,或者如何使用setTimeout呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个音乐程序,该程序需要多个JavaScript元素才能彼此同步.我一直在使用setInterval,起初效果很好.但是,随着时间的流逝,元素逐渐变得不同步,这在音乐程序中是很糟糕的.

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 is bad in a music program.

我已经在线阅读了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.

基本上我有一些像这样的功能:

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无限循环的基本示例吗?另外,如果有一种方法可以通过setInterval甚至其他功能获得更多同步结果,请告诉我.

Could someone just show me a basic example of using setTimeout to loop something indefinitely? Alternatively, if there is a way to achieve more synchronous results with setInterval or even another function, please let me know.

推荐答案

您可以使用递归创建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.

这篇关于如何使setInterval表现得更加同步,或者如何使用setTimeout呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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