set timeout to event listener function
Asked Answered
H

4

6

I have an event listener

elem.addEventListener('evt', fooFn(){alert("OK")});

I would like to have a timeout for this event listener. So let's say that if it doesn't receive any event called 'evt' in 3 seconds I would like to have a notification that it timed out.

I tried with the setTimeout function but so far I don't manage to pass an internal variable of the addEventListener callback function (fooFn) to the setTimeout one.

Any ideas on how I could make it?

Hootenanny answered 24/4, 2017 at 9:5 Comment(1)
Can you try to rewrite your requirements more clearly? does the event trigger a timeout or does the event cancel the timeout, or both?Shortfall
E
6
var evtFired = false;
setTimeout(function() {
    if (!evtFired) {
      // show notification that evt has not been fired
    }
}, 3000);

function fooFn() {
    evtFired = true;
    alert('OK');
}

elem.addEventListener('evt', fooFn);

maybe this will work, just place the "internal variable" in the outer scope

Esthonia answered 24/4, 2017 at 9:12 Comment(0)
A
5

I think this should work.

 function addTimeoutEvent(elem){
   var timeout = setTimeout(function(){
      alert('the time is out');
      elem.removeEventListener('evt',foo)
   },3000);
   elem.addEventListener('evt', foo);
   function foo (){
     if(timeout)
       clearTimeout(timeout);
     alert("OK")
   }
 }
Adrea answered 24/4, 2017 at 9:17 Comment(0)
A
1

Try such (it seems to me to be the way for the least processor and memory consumption):

  var timeMEM = Math.trunc(Date.now()/1000)

  'target'.addEventListener('event', function(){
     if(data < Math.trunc(Date.now()/1000)){

        // do something in one second periods

        timeMEM = Math.trunc(Date.now()/1000);
     }
  });
Aramen answered 2/5, 2021 at 16:13 Comment(0)
L
0

Try the following solution:

let btn = document.getElementById('btn');

let timeOut = setTimeout(() => {
  btn.removeEventListener('click', handler);
  alert('no event on btn');
}, 3000);

let handler = x => {
  clearTimeout(timeOut);
  alert('click on btn')
};

btn.addEventListener('click', handler);
<button id="btn">click me within 3 sec</button>
Lavinialavinie answered 24/4, 2017 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.