How to trigger an event after n seconds of a supported click? - jQuery / Javascript

I am sure that I am not the first to seek this, but I have not found a solution to my problem.

I am looking for a way to trigger an event after and only after 3 seconds of a supported click. I tried using the javascript setInterval () function with jQuery mouseup / mousedown events, but it did not work.

Does anyone have an idea?

I have a div, I hold the mouse button for 3 seconds and something will be fired. The 3 second timer must be reinitialized every time.

+4
source share
5 answers

Call setTimeout() to complete its action after 3000 milliseconds, storing the identifier from setTimeout() in a variable bounded above the function. On the mouseup() element, clear the timeout if it exists through clearTimeout() .

 var divMouseDown; $('#div-id').mousedown(function() { divMouseDown = setTimeout(function() { // Do timeout action... }, 3000); }); $('#div-id').mouseup(function() { if (divMouseDown) { clearTimeout(divMouseDown); } }); 
+10
source

While holding the mouse, set the timeout for 3 seconds in the future.

Use the mouse to clear the timeout.

+1
source

It seems that mouseup / mousedown events and setTimeout / clearTimeout are a way to do this:

 var timer = null; $(selector).on('mousedown', function(ev) { timer = setTimeout(function() { timer = null; /* Do something */ }, 3000); }.on('mouseup', function(ev) { if (timer) { clearTimeout(timer); timer = null; } }); 
+1
source
 $('#div').on('mousedown', function(){ mousetimer.down(); }).on('mouseup', function(){ mousetimer.cancel(); }); var mousetimer = { timer: null, timing: false, down: function(){ if(!timing) { mousetimer.timing = true; mousetimer.timer = setTimeout(function(){ mousetimer.trigger(); }, 3000); } }, trigger: function(){ alert('do something'); mousetimer.cancel(); }, cancel: function(){ mousetimer.timing = false; clearTimeout(mousetimer.timer); } }; 
+1
source

Use a 3000 ms timeout.

Set timeout on mouse event, clear it on mouse event.

http://jsfiddle.net/kHMWX/

0
source

Source: https://habr.com/ru/post/1397534/


All Articles