防止 javascript setInterval 函数堆积 [英] prevent javascript setInterval function stacking up

查看:78
本文介绍了防止 javascript setInterval 函数堆积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在单击事件上运行的函数,该函数对我的某些动画使用 javascript 的 setIterval(我正在做游戏),所以问题是如果用户在动画仍在显示时单击(setInterval 仍在执行)) setInterval 正在事件堆栈中堆积,或者这就是我发现的结果,因此要么破坏我的游戏,要么以两倍的速度运行(动画).我的问题是有什么方法可以防止事件堆叠?我不希望 setInterval 叠加在之前的 setInterval 上等等.我知道我可以像这样使用 clearInterval 函数:

I have a function that runs on a click event that uses javascript's setIterval for some of my animations (i'm doing a game) so the problem is that if a user clicks while the animation is still displaying (setInterval is still executing) the setInterval is stacking up in the event stack or that is what I found out thus either crushing my game or running twice as fast (the animation). My question is is there any way to prevent event stacking? I do not want the setInterval to stack up on the previous setInterval and so on. I know that I could use clearInterval function like so:

  var timerInterval = setInterval(drawPlayerRunning, 50);
  clearInterval(timerInterval);

但它并没有像我想要的那样真正工作,因为如果用户在函数仍在执行时多次单击会怎样,clearInterval 只会摆脱事件堆栈的最后一个事件,而保留所有先前的事件游戏".知道如何防止此事件堆积,或至少有效地删除它们吗?

but it does not really work as I want it to, because what if user clicks many times while the function is still is executing, the clearInterval will only get rid of last event of the event stack leaving all the previous ones still in the "game". Any idea how to prevent this event stack up, or at least removing them efficiently?

推荐答案

您可以创建一个标志来监视间隔状态:1)

You can create a flag that monitors the interval state: 1)

var isIntervalInProgress = false;
setInterval(function()
{
  if ( isIntervalInProgress )
    return false;

  isIntervalInProgress = true;

  drawPlayerRunning();

  isIntervalInProgress = false;

}, 50);

或者只是一个超时,一旦完成就会自行运行:2)

or just a timeout that will run itself once it's finished: 2)

var func = function()
{
  setTimeout(function()
  {
    drawPlayerRunning();
    func();
  }, 50)
}

随便你

这篇关于防止 javascript setInterval 函数堆积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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