2016-08-03 67 views
1

当我按下鼠标中键时,它会在一秒钟后在控制台显示“1秒后”。没关系,这是我需要的。但是如果我释放鼠标中键(mouseup listener),我也想停止1秒的延迟。但是,现在'wait'函数执行'mouseup'时,监听器当然不会将'delay'变量改为false(仅在1秒后通过)。但是MB有什么办法可以做到吗? (停止“等待”功能,例如当其延迟0.5秒的鼠标松开中间按钮,而不是1秒)使用getTime的停止/中断函数执行

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");,我们能延缓副本剪贴板最大的Chrome浏览器1秒使用setTimeout() FUNC,但它不会在Firefox与setTimeout()工作,但wait(999); document.execCommand('copy');作品火狐(999毫秒允许的最大值)

回答

1

你的问题是,鼠标按下监听功能会阻止进一步的执行直到完成。您的等待功能实现了所谓的“繁忙等待”。您应该使用setTimeout(),它允许您在特定时间后异步执行函数。你从setTimeout()得到一个句柄,如果你释放鼠标键,你可以用它来中止超时。有关更多信息,请参阅https://developer.mozilla.org/en/docs/Web/API/WindowTimers/setTimeout

+0

我应该提到我真正想要的东西。我将使用'setTimeout()'在Chrome浏览器中将拷贝延迟到剪贴板的最大时间为1秒(1秒钟后);''用'document.execCommand(“copy” 'func,但它不能用'setTimeout()'在Firefox中工作,但是'wait(999); document.execCommand('copy');'适用于Firefox(最多允许999毫秒)。 – user25

+0

那么如果你不能从setTimeout()复制剪贴板,那么你就没有办法了。繁忙的等待将永远阻止你的mouseup事件。 –