user25
user25

Reputation: 3215

Stop/interrupt function execution which works with getTime

When I press middle mouse button it shows "after 1 sec" in console after one second. It's ok, it's what I need. But I also want to stop 1 sec delay if I release middle mouse button (mouseup listener). But now while 'wait' function executes 'mouseup' listener of course will not change 'delay' variable to false (only after 1 sec was passed). But mb is there any way I can do it? (to stop 'wait' function, e.g. when it delayed 0.5 sec on mouseup middle button, not 1 sec)

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;
    }
});

update: I'm going to replace console.log("after 1 sec"); with document.execCommand("copy");, We can delay copy to clipboard maximum for 1 sec in Chrome browser using setTimeout() func, but it won't work in Firefox with setTimeout(), but wait(999); document.execCommand('copy'); works for Firefox (999 ms maximum allowed)

Upvotes: 1

Views: 101

Answers (1)

Dennis B.
Dennis B.

Reputation: 1577

Your problem is that the mousedown listener function will block further execution until it finishes. Your wait function implements so called "busy waiting". You should use setTimeout() which allows you to execute a function asynchronously after a specific time. You get a handle back from setTimeout() which you can use to abort the timeout if you release the mouse button. See https://developer.mozilla.org/en/docs/Web/API/WindowTimers/setTimeout for more information.

Upvotes: 1

Related Questions