使用getTime的停止/中断函数执行

Stop/interrupt function execution which works with getTime

本文关键字:中断 函数 执行 getTime 使用      更新时间:2023-09-26

当我按下鼠标中键时,它会在控制台中显示"1秒后"。没关系,这正是我需要的。但如果我释放鼠标中键(mouseup监听器),我也想停止1秒的延迟。但现在,当"wait"函数执行"mouseup"时,侦听器当然不会将"delay"变量更改为false(仅在经过1秒之后)。但是mb有什么办法我能做到吗?(停止"等待"功能,例如当鼠标中键延迟0.5秒,而不是1秒时)

function wait(ms){
   var start = new Date().getTime();
   var end = start;
   while((end < start + ms) && delay == true) {
     end = new Date().getTime();
  }
}
var delay = false;
document.addEventListener("mousedown", function(e) {
    if (e.button == 1) { // 1 - middle mouse button
        delay = true;
        wait(1000); // delay 1 sec
        console.log("after 1 sec");
    }
});
document.addEventListener("mouseup", function(e) {
    if (e.button == 1) { 
        delay = false;
    }
});

更新:我将用document.execCommand("copy");替换console.log("after 1 sec");,我们可以使用setTimeout()函数在Chrome浏览器中延迟复制到剪贴板最多1秒,但它在带有setTimeout()的Firefox中不起作用,但wait(999); document.execCommand('copy');适用于Firefox(最多允许999毫秒)

您的问题是mousedown监听器函数将阻止进一步执行,直到它完成。您的等待函数实现了所谓的"繁忙等待"。您应该使用setTimeout(),它允许您在特定时间后异步执行函数。您可以从setTimeout()获得一个句柄,如果释放鼠标按钮,可以使用该句柄中止超时。看见https://developer.mozilla.org/en/docs/Web/API/WindowTimers/setTimeout了解更多信息。