在mousedown上不断重复功能

时间:2016-10-14 17:12:27

标签: javascript

我正在制作一支笔,您可以通过点击进行拍摄,或者您可以按住,但是我不知道如何让事件一遍又一遍地重复。 你可以在这里看到它:http://codepen.io/TheAndersMan/pen/gwKmYy?editors=0111

但为了保持简单,我只想举个例子:

document.querySelector("body").addEventListener("mouseDown", function() {
    console.log(123)
})

我希望我可以设置一个间隔,让它每隔一秒或半秒做一次。

提前致谢!

2 个答案:

答案 0 :(得分:5)

使用Interval
Clear它在mouseup上



var fireRate = 20,
    fireInterval = null;

function fire() {
   console.log("BAM!");
}

function startFire() {
   fire();
   fireInterval = setInterval(fire, 1000/fireRate );
}

function stopFire() {
   clearInterval(fireInterval);
}

document.addEventListener("mousedown", startFire);
document.addEventListener("mouseup", stopFire);

html, body{height:100%;}




答案 1 :(得分:1)

您可以为mousedown事件添加事件侦听器,并在回调中使用setInterval()以设置的间隔(例如500毫秒)调用该函数。然后观察mouseup并在回调中使用mouseup上的clearInterval()来清除间隔。见下面的例子:



var interval; //set scope here so both functions can access it
document.addEventListener("mousedown", function() {
  fireFunction();
  interval = setInterval(fireFunction, 500); //500 ms - customize for your needs
});
function fireFunction() {
  console.log(123); //replace with your code for firing 
}
document.addEventListener("mouseup", function() {
  if (interval ) {
    clearInterval(interval );
  }
});




相关问题