How to trigger an event in the input text after the termination of input / recording?

I want to trigger an event right after I stop typing (not during input) characters in the input text box.

I tried:

$('input#username').keypress(function() { var _this = $(this); // copy of this object for further usage setTimeout(function() { $.post('/ajax/fetch', { type: 'username', value: _this.val() }, function(data) { if(!data.success) { // continue working } else { // throw an error } }, 'json'); }, 3000); }); 

But this example creates a timeout for each typed character, and I get about 20 AJAX requests if I enter 20 characters.

In this script, I demonstrate the same problem with a simple warning, not with AJAX.

Is there a solution for this, or am I just using a bad approach for this?

+65
jquery timeout keypress typeahead debouncing
Dec 26 '12 at 14:48
source share
8 answers

You will need to use setTimeout (like you), but also keep the link so you can reset the limit. Something like:

 // // $('#element').donetyping(callback[, timeout=1000]) // Fires callback when a user has finished typing. This is determined by the time elapsed // since the last keystroke and timeout parameter or the blur event--whichever comes first. // @callback: function to be called when even triggers // @timeout: (default=1000) timeout, in ms, to to wait before triggering event if not // caused by blur. // Requires jQuery 1.7+ // ;(function($){ $.fn.extend({ donetyping: function(callback,timeout){ timeout = timeout || 1e3; // 1 second default timeout var timeoutReference, doneTyping = function(el){ if (!timeoutReference) return; timeoutReference = null; callback.call(el); }; return this.each(function(i,el){ var $el = $(el); // Chrome Fix (Use keyup over keypress to detect backspace) // thank you @palerdot $el.is(':input') && $el.on('keyup keypress paste',function(e){ // This catches the backspace button in chrome, but also prevents // the event from triggering too preemptively. Without this line, // using tab/shift+tab will make the focused element fire the callback. if (e.type=='keyup' && e.keyCode!=8) return; // Check if timeout has been set. If it has, "reset" the clock and // start over again. if (timeoutReference) clearTimeout(timeoutReference); timeoutReference = setTimeout(function(){ // if we made it here, our timeout has elapsed. Fire the // callback doneTyping(el); }, timeout); }).on('blur',function(){ // If we can, fire the event since we're leaving the field doneTyping(el); }); }); } }); })(jQuery); $('#example').donetyping(function(){ $('#example-output').text('Event last fired @ ' + (new Date().toUTCString())); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" id="example" /> <p id="example-output">Nothing yet</p> 

This will be done when:

  • Timed out or
  • Fields entered by the user ( blur event)

(Whichever comes first)

+141
Dec 26 '12 at 14:52
source share

DECISION:

Here is the solution. Executing a function after the user has stopped typing for a certain amount of time:

 var delay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); 

Using

 $('input').keyup(function() { delay(function(){ alert('Hi, func called'); }, 1000 ); }); 
+51
Aug 28 '13 at 10:00
source share

You can use underscore.js "debounce"

 $('input#username').keypress( _.debounce( function(){<your ajax call here>}, 500 ) ); 

This means that your function call will be executed after 500 ms of keystroke. But if you press another key (another keypress event) before 500 ms, the previous function execution will be ignored (canceled), and the new one will be executed after the new 500 ms timer.

For more information, using the _.debounce function (func, timer, true ) means that the first function will be executed, and all other keystroke events followed by 500 ms timers will be ignored.

+15
Jun 11
source share

You need to debut!

Here is the jQuery plugin and that’s all you need to know about debounce . If you come here from Google, and Underscore found its way into your application's JSoup, it has debounce baked right in !

+9
Nov 06 '13 at 9:47
source share

purified solution:

 $.fn.donetyping = function(callback, delay){ delay || (delay = 1000); var timeoutReference; var doneTyping = function(elt){ if (!timeoutReference) return; timeoutReference = null; callback(elt); }; this.each(function(){ var self = $(this); self.on('keyup',function(){ if(timeoutReference) clearTimeout(timeoutReference); timeoutReference = setTimeout(function(){ doneTyping(self); }, delay); }).on('blur',function(){ doneTyping(self); }); }); return this; }; 
+3
Feb 24 '15 at 11:48
source share

There are a few simple plugins that I have made that make this much deeper. It requires much less code than the proposed solutions, and it is very lightweight (~ 0.6kb)

First you create a Bid object than can be bumped at any time. Each hit slows the Bid callback for the next specified time.

 var searchBid = new Bid(function(inputValue){ //your action when user will stop writing for 200ms. yourSpecialAction(inputValue); }, 200); //we set delay time of every bump to 200ms 

When the Bid object is ready, we need to bump it somehow. Let the slope be attached to the keyup event .

 $("input").keyup(function(){ searchBid.bump( $(this).val() ); //parameters passed to bump will be accessable in Bid callback }); 



What is going on here:

Each user presses a key, the bet is "delayed" (filled) for the next 200 ms. If 200 ms pass without unnecessary hits, the callback will be launched.

In addition, you have two additional functions for stopping the bet (if the user pressed esc or pressed an external input, for example), as well as for immediate completion and immediate completion of the callback (for example, when the user presses the enter key):

 searchBid.stop(); searchBid.finish(valueToPass); 
+3
Apr 23 '15 at 11:39 on
source share

I was looking for simple HTML / JS code and I did not find it. Then I wrote the code below using onkeyup="DelayedSubmission()" .

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br"> <head><title>Submit after typing finished</title> <script language="javascript" type="text/javascript"> function DelayedSubmission() { var date = new Date(); initial_time = date.getTime(); if (typeof setInverval_Variable == 'undefined') { setInverval_Variable = setInterval(DelayedSubmission_Check, 50); } } function DelayedSubmission_Check() { var date = new Date(); check_time = date.getTime(); var limit_ms=check_time-initial_time; if (limit_ms > 800) { //Change value in milliseconds alert("insert your function"); //Insert your function clearInterval(setInverval_Variable); delete setInverval_Variable; } } </script> </head> <body> <input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" /> </body> </html> 
0
Feb 22 '15 at 1:25
source share

In my opinion, the user stops writing when he does not focus on this input. To do this, you have a β€œblur” function that makes the material like

-2
Dec 26
source share



All Articles