javascript - 按下按钮时每秒执行一次javascript函数
问题描述
我需要连续执行一个javascript函数(例如每隔一秒或半秒),但这需要在按下按钮时发生。
我尝试了以下方法:
$("#buttonID").bind('touchstart',function(event){
setInterval(function() {
FUNCTION
}, 1000);
});
它也不是那样工作,使用“mousedown”。
它在 JavaScript 问题上的回答,而 mousedown 没有解决我的问题,所以我不认为这个问题是重复的。
是否有初学者的错误,我没有看到它?你有什么建议?
解决方案
您必须捕获对计时器的引用并在释放鼠标时取消它。
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>
推荐阅读
- reactjs - 如何在 React 中正确地 fetch() JSON
- java - 使用 while 循环将多个 LinearLayout 添加到滚动视图中
- google-sheets - 如何从包含多个值的单元格中计算一个值?
- zend-framework - zend framework 3 如何在控制器中调用 phtml 文件
- php - 在 Windows 中使用 php 执行 aws cli - 错误未知编码
- python - /posts/create/ int() 的 ValueError 以 10 为基数的无效文字:在 django 表单中“创建”
- c - i2c_master_recv 的价值从何而来?
- jquery-ui - jQuery UI DatePicker:排除天数+日期
- ionic-framework - 离子cordovarduino java.lang.ArrayIndexOutOfBoundsException
- html - 用 svg-icon 剪辑出彩虹动画