开发者

Preventing a callback from executing until input stops

A timer to fire an AJAX call if no key is pressed. If a key is pressed, then abort the last timer and add a new timer. That is what I want to do but failed to success. Here is my code:

 var t;
 input.onkeyup = function(){
    $('.confirmText').html('Checking...');
    var timeStampObj = new Date()
    var timeStamp = timeStampObj.getTime();
    var oldTimeStamp = $(this).attr('timeStamp');//I store a timeStamp in the element
    if(timeStamp < 500 + oldTimeStamp){
        $(this).attr('timeStamp', timeStamp);
        clearTimeout(t);
    }
    t = setTimeout(function(){
        $开发者_JAVA百科.ajax({
            url: 'serverScripts/settings/checkEmailAvailability.php',
            data: 'email='+email,
            success: function(text){

           if(text == 'available'){
                $('.confirmText').html('Available!');
           }else{
                $('.confirmText').html('Occupied!');
               }
            }
        });
    }, 500);//Half a second
    $(this).attr('timeStamp', timeStamp);
}


It sounds like you're asking for a debouncer. The term comes from electronics. It's a way to prevent multiple events from firing within some time threshold. You can use the following function to create a new function that will only be called if a given amount of time has passed since the 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 to debounce won't execute as long as click events keep firing.

The excellent Underscore.js library includes an equivalent function and there are at least a couple jQuery plugins:

  • http://code.google.com/p/jquery-debounce/
  • http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/


Where do you define the email variable in your JavaScript?

You need to define email somewhere and then check to see if your script works.

var email = $(this).value; // Pseudo-code - are you using jQuery?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜