简体   繁体   中英

Set delay within event

My code -

hits.on('rowSelected', function (evt) {
    setTimeout(function() { alert('hi'); }, 5000); 
});

so I have a hits table. When a row is selected within that table, this event gets fired. The issue is I want to not be able to select a row again for 5 seconds. IMO, this isn't working because the event on the table gets fired every time a row is selected without giving the setTimeout time to delay.

Is there a better way?

What I would recommend is making use of a variable to store whether the element has been clicked or not.

Run your setTimeout() inside an if conditional that checks against this variable. Once the element is clicked, update the variable so that it cannot be clicked again. Then, once the timeout has resolved, enable the click again.

This can be seen in the following:

 var hits = $("p"); var clickable = true; // It's clickable by default hits.on('click', function(evt) { if (clickable) { // Check whether it can be clicked clickable = false; // Once clicked, don't allow further clicks setTimeout(function() { alert('hi'); clickable = true; // Make it clickable again }, 5000); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Click this paragraph.</p> 

Hope this helps! :)

The most elegant solution I could come up with is below, using a button to simulate the behavior.

It works as follows:

  1. Bind a named event handler ( handler ) to the element, and use jQuery's one() to only execute it once.
  2. In the event handler, handle the event.
  3. Use setTimeout() to wait 5 seconds before re-binding the event handler for the next execution.

 let button = $('#button'); button.one('click', function handler() { console.log('clicked'); // handle event here setTimeout(() => $(this).one('click', handler), 5000); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button">Click me!</button> 

This approach has the following benefits:

  • Does not require external variables to hold the state of the event handler (ie whether it's active or not).
  • Does not require unbinding of the event handler, as every time it's only bound for only a single execution.
  • Does not pollute the outer scope with a named event handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM