Some types of events like mousemove and scroll events fires many times. Any time-consuming actions inside your handler will make interaction with the document starts to feel slow and choppy.

You can use setTimeout to make sure you are not doing it too often. This is usually called debouncing the event.

For example when the user has typed something, instead of immediately performing an action in the event handler we wait until a pause occurs. Set a timeout and also clear the previous timeout (if any) so that when events occur close together (closer than our timeout delay), the timeout from the previous event will be canceled.

var textarea = document.querySelector( & quot; textarea & quot;);
var timeout;
textarea.addEventListener( & quot; keydown & quot;, function() {
    timeout = setTimeout(function() {
        console.log( & quot; You stopped typing. & quot;);
    }, 500);

For example, shows the current coordinates of the mouse using "mousemove" events, but only every 250 milliseconds.

function displayCoords(event) {
    document.body.textContent = 'Mouseat' + event.pageX + ', ' + event.pageY;

var scheduled = false,  lastEvent;

addEventListener( & quot; mousemove & quot;, function(event) {
    lastEvent = event;

    if (!scheduled) {
        scheduled = true;

        setTimeout(function() {
            scheduled = false;
        }, 250);
Related Tutorial
Follow Us #
Contents +