【问题标题】:Execute javascript function every second while the button is pressed [duplicate]按下按钮时每秒执行一次javascript函数[重复]
【发布时间】:2018-11-05 05:44:21
【问题描述】:

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

我尝试了以下方法:

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

使用“mousedown”也不行。

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

是否存在初学者的错误而我没有看到?你有什么建议?

【问题讨论】:

  • 请展示您使用 mousedown 事件的尝试!
  • 您使用的是什么版本的 jQuery?尝试 .on() 而不是 .bind()
  • 为什么要使用 bind()?你应该使用 on() 除非你使用的是旧版本的 jQuery。

标签: javascript jquery


【解决方案1】:

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

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多