基本上我要做的是,我试图调用功能并在每次“ n ”秒后重复相同的功能,直到按下鼠标按钮按钮/图片上的( MouseDown ),并在释放鼠标按钮时停止调用该功能( MouseUp )。我正在尝试使用 JavaScript !
执行此操作一些参考资料
答案 0 :(得分:1)
未经测试,但提出了一个想法。
var state = false;
function repeatingFunction(){
if (!state){
return;
}
console.log("Do something");
setTimeout(repeatingFunction, 2000);
}
function mymousedown(ev){
state = true;
repeatingFunction();
}
function mymouseup(ev){
state = false;
}
var obj = document.getElementById("foo");
obj.addEventListener("mousedown", mymousedown);
obj.addEventListener("mouseup", mymouseup);
答案 1 :(得分:0)
这应该适合你:
var timerId = 0;
function onmousedown(ev) {
console.log("Do something"); //first call right after mouse down
timerId = setInterval(function () {
console.log("Do something");
}, 2000);
}
function onmouseup(ev) {
clearInterval(timerId);
}
var obj = document.getElementById("foo");
obj.addEventListener("mousedown", onmousedown);
obj.addEventListener("mouseup", onmouseup);