Does jQuery have a built-in way to do this?
No.
If not, is there a better template for this in vanilla JS than I used in my second jsfiddle example?
Instead of using setTimeout and flags, you can track when the handler was called the last time, and only call it after a certain interval. This is called throttling , and there are various ways to implement it.
In its simplest form, you just need to ignore every call that is made during the lastCall + interval , so that there is only one call in each interval.
eg. here is a function that returns a new function that can only be called every millisecond:
function throttle(func, interval) { var lastCall = 0; return function() { var now = Date.now(); if (lastCall + interval < now) { lastCall = now; return func.apply(this, arguments); } }; }
which you can use as
$("#inputField").on("keypress", throttle(function(event) { $("div#output").append("key pressed <br/>"); }, 500));
Demo
As Esailija mentions in his comment , this may not be the throttling you need, but a chatter . This is a similar, but slightly different concept. Although throttling means that something should happen only once every milliseconds, debouncing means that something should only happen if it didn't happen in the last milliseconds.
A typical example is the scroll event. The scroll event handler will be called very often, because the event is mostly fired continuously. But perhaps you only need to execute the handler when the user stops scrolling, and not while he is scrolling.
An easy way to achieve this is to use a timeout and cancel it if the function is called again (and the timeout has not yet been started):
function debounce(func, interval) { var lastCall = -1; return function() { clearTimeout(lastCall); var args = arguments; var self = this; lastCall = setTimeout(function() { func.apply(self, args); }, interval); }; }
The disadvantage of this implementation is that you cannot return a value from an event handler (for example, return false; ). Perhaps there are implementations that can save this function (if required).
Demo