Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

javascript - 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(){
        $.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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...