2014-04-26 59 views
0


对于决定回答这个问题的人,我突然遇到了一个小问题。
我尝试做以下:Javascript set/clearInterval assist

创建

var intrvl; //for interval 
function strt() { 
    //and set interval 
    intrvl = setInterval(writeT,3000); 
} 
function writeT() { 
    //do something here as the interval runs 
    checkIf(); //check for the mouse down 
} 
function checkIf() { 
    //here goes the code that checks if mouse is down and if it is 
    //then I call another function that begins other useful process 
    //I tried 
    if (c.addEventListener('click')) { //c is my canvas 
      clearInterval(intrvl); //guess clearing the interval yee? 
      //and then calling the function I want to call 
      startDoing(); 
    } 
} 

我要等待,直到有人点击画布上使用间隔,然后运行所需的功能。
但是,无论何时点击画布,函数startDoing()都会运行,但与运行它相比,运行速度太快而没有这一切。
如何让它工作?正如我想要的那样,首先创建的时间间隔不存在,只有startDoing()运行。

回答

1

你误解了addEventListener()的使用。

您的checkIf()中的情况正在立即返回。因此,你的代码是

  1. 上调用strt()
  2. 早在间隔定时器增加点击处理程序启动间隔定时是首次
  3. 流逝而且它会立即停止间隔时间ER和调用startDoing()然后。

使用它一样,而不是:

var intrvl; 
var clicked = false; 

function strt() { 
    //and set interval 
    intrvl = setInterval(checkIf,3000); 
} 

function checkIf() { 
    if (clicked) { 
     clearInterval(intrvl); 
     startDoing(); 
    } 
} 

c.addEventListener('click', function() { 
    clicked = true; 
}); 

这个码立即注册点击处理。只要调用strt(),它就会启动间隔计时器。一旦鼠标被点击,被点击的变量被设置为真以标记该事件。下一次您的间隔计时器触发时,它会识别先前的点击,因为检查该变量并启动您想要启动的任何内容。