首页 > 解决方案 > 按下按钮时每秒执行一次javascript函数

问题描述

我需要连续执行一个javascript函数(例如每隔一秒或半秒),但这需要在按下按钮时发生。

我尝试了以下方法:

$("#buttonID").bind('touchstart',function(event){ 
        setInterval(function() {
            FUNCTION
        }, 1000);
    });

它也不是那样工作,使用“mousedown”。

它在 JavaScript 问题上的回答,而 mousedown 没有解决我的问题,所以我不认为这个问题是重复的。

是否有初学者的错误,我没有看到它?你有什么建议?

标签: javascriptjquery

解决方案


您必须捕获对计时器的引用并在释放鼠标时取消它。

var timer = null; // Will hold a reference to the timer

$("#buttonID").on('mousedown',function(event){ 
 // Set the timer reference
 timer = setInterval(function() {
   console.log("Function running");
 }, 1000);
});

$("#buttonID").on('mouseup',function(event){ 
 clearInterval(timer);  // Cancel the timer
 console.log("Timer cancelled.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonID">Hold me down to run function!</button>


推荐阅读