luthien
luthien

Reputation: 1305

set timeout to event listener function

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?

Upvotes: 6

Views: 24613

Answers (4)

Marek Wysmułek
Marek Wysmułek

Reputation: 961

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

Upvotes: 1

GibboK
GibboK

Reputation: 73928

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>

Upvotes: 0

Anton Stepanenkov
Anton Stepanenkov

Reputation: 1036

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

Upvotes: 5

Freeman Lambda
Freeman Lambda

Reputation: 3655

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

Upvotes: 6

Related Questions