javascript - Preventing a callback from executing until input stops -


a timer fire ajax call if no key pressed. if key pressed, abort last timer , add new timer. want failed success. here code:

 var t;  input.onkeyup = function(){     $('.confirmtext').html('checking...');     var timestampobj = new date()     var timestamp = timestampobj.gettime();     var oldtimestamp = $(this).attr('timestamp');//i store timestamp in element     if(timestamp < 500 + oldtimestamp){         $(this).attr('timestamp', timestamp);         cleartimeout(t);     }     t = settimeout(function(){         $.ajax({             url: 'serverscripts/settings/checkemailavailability.php',             data: 'email='+email,             success: function(text){             if(text == 'available'){                 $('.confirmtext').html('available!');            }else{                 $('.confirmtext').html('occupied!');                }             }         });     }, 500);//half second     $(this).attr('timestamp', timestamp); } 

it sounds you're asking debouncer. term comes electronics. it's way prevent multiple events firing within time threshold. can use following function create new function called if given amount of time has passed since last event.

function debounce(callback, timeout, _this) {     var timer;     return function(e) {         var _that = this;         if (timer)             cleartimeout(timer);         timer = settimeout(function() {              callback.call(_this || _that, e);         }, timeout);     } }  // requires jquery $("div").click(debounce(function() {     console.log("tset"); }, 2000)); 

the callback given debounce won't execute long click events keep firing.

the excellent underscore.js library includes an equivalent function , there @ least couple jquery plugins:


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -