如何在无限循环中执行3秒后执行代码
我正在使用HTML帆布进行游戏,我想在其中每次都在动画循环中检查某些条件,如果该条件变为真实,那么我不想检查接下来的3秒钟,并且3秒钟后,我想再次检查。像
function animate(){
requestAnimationFrame(animate)
if (checking something){
if this if statement gets executed then don't check this if statement for next 3 seconds
}
这听起来有些混乱,但无论如何都可以做到这一点。
I am making a game using html canvas in which i want to check for certain condition every time in animate loop and if that condition become true once then I don't want to check for next 3 seconds and after 3 seconds i want to check again. Like
function animate(){
requestAnimationFrame(animate)
if (checking something){
if this if statement gets executed then don't check this if statement for next 3 seconds
}
This might sound bit confusing but is there anyway to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的建议是添加一个标志 - 您可以用来检查是否应该完成操作的另一个变量,以及在一定时间之后切换标志的另一个功能。
My suggestion would be to add a flag - another variable that you can use to check if an operation should be done, and another function that'll toggle the flag after a certain amount of time.
如果您想在另一种方法中内联行动,SetInterval可能无济于事。
您只需记下您上次进行检查(例如,以毫秒为单位的系统时间),然后确保下一次进行检查后的检查时间超过3000ms。
您可以有两个
var
slastcheckedtime
和currenttime
。If you want to do it inline within another method, setInterval might not help.
You can just make a note of the last time you did that check (eg. system time in milliseconds) and then make sure that it is more than 3000ms after that when you next do the check.
You can have two
var
slastCheckedTime
andcurrentTime
.requestAnimationFrame
尝试在下一个帧上运行,而不是三秒钟后。因此,如果要三秒钟,请不要使用requestAnimationFrame
。requestAnimationFrame
tries to run on the next frame, not after three seconds. So don't userequestAnimationFrame
if you want three seconds.