2

I'm adding following event, which simply updates a variable with the actual time:

$(document).keyup(function () {
    lastAction = new Date();
});

Now I'm wondering if this will decrease the browser performance? Would it be better to remove the event from document and add it with a timer (e.g. after 1s) again, so that not every keyup will fire?

$(function () {

    $(document).keyup(actionevent);

});

function actionevent() {
    lastAction = new Date();
    $(document).off("keyup", actionevent);

    intervalId = setTimeout(function () {
        $(document).keyup(actionevent);
    }, 1000);
}
Phoniex
  • 171
  • 9
  • Your first code example is far better than the second. However without knowing your exact requirements it's possible there's another approach you can use. From the context I assume you want to perform an action when the user is inactive for a set amount of time? – Rory McCrossan Jun 16 '20 at 10:00
  • Does this answer your question? [javascript/jquery - add debounce to a button](https://stackoverflow.com/questions/8055923/javascript-jquery-add-debounce-to-a-button) – Justinas Jun 16 '20 at 10:02
  • @RoryMcCrossan: Yes I have some kind of timer which makes periodic ajax calls to the server, if there was no user action (keyup, click) for an amount of time the ajax calls should stop. For this I have to know when the last user action happened. – Phoniex Jun 16 '20 at 10:12
  • 1
    In which case use the first code example, and check the difference between current time and `lastAction` before making the AJAX call – Rory McCrossan Jun 16 '20 at 10:22
  • @Justinas: I know about this soultion, but the question was more like if it is necessary to do so (in case I have to expect a performance issue for my first code example) – Phoniex Jun 16 '20 at 10:30
  • @Phoniex Depends on inner code. If it's simple one line, then it's good to go with first example. But for example you have `$(window).resize` that triggers on every pixel resized (or even more) then you need to apply debounce. – Justinas Jun 16 '20 at 10:37
  • If you were making the ajax call on every keyup, then you would want to *debounce* that keyup so that the call only runs after they've finished typing, but that's neither of the code samples you have. – freedomn-m Jun 16 '20 at 11:24

0 Answers0