最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - set timeout to event listener function - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Apr 24, 2017 at 9:05 luthienluthien 1,3054 gold badges16 silver badges27 bronze badges 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? – Touffy Commented Apr 24, 2017 at 9:11
Add a comment  | 

4 Answers 4

Reset to default 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

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

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

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>

发布评论

评论列表(0)

  1. 暂无评论