How to ignore all except the last one of a series of quick Javascript events?

events, javascript, keyboard-events

Solution

The classic way is to use a short timeout:

var cursorTimer;
function changeCursor() {
    clearTimeout(cursorTimer);
    cursorTimer = setTimeout(function() {
        // process the actual cursor change here
    }, 500);

}

Your regular code can continue calling `changeCursor()` every time it changes (just like it does now), but the actual code inside the `setTimeout()` will only execute when no cursor change events have occurred in the last 500ms. You can adjust that time value as desired.

The only way to know that events have stopped is to wait some short period of time and detect no further movement (which is what this does). It is common to use similar logic with scroll events.

Problem

One of my script calls a function at some point, due to a 'changeCursor' event (I am using ACE editor). This slows down the movement of the cursor when I press it many times. I really want this function to be called, but it's fine if it is only called once my cursor stopped moving (i.e. I do not need to see intermediary states). Is there a standard way to have all but the last event ignored?

Original source