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.
<textarea>Typesomethinghere...</textarea>
<script> var textarea = document.querySelector( & quot; textarea & quot;); var timeout; textarea.addEventListener( & quot; keydown & quot;, function() { clearTimeout(timeout); timeout = setTimeout(function() { console.log( & quot; You stopped typing. & quot;); }, 500); }); </script>
For example, shows the current coordinates of the mouse using "mousemove" events, but only every 250 milliseconds.
<script> 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; displayCoords(lastEvent); }, 250); } }); </script>