Prevent callback before stopping login

Timer to start an AJAX call if no key is pressed. If you press a key, cancel the last timer and add a new timer. This is what I want to do, but could not succeed. 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);
}
+3
source share
2 answers

Sounds like you're asking for a newcomer. The term comes from electronics . This is a way to prevent multiple trips within a certain time threshold. You can use the following function to create a new function that will only be called if a certain 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));

, debounce, , .

Underscore.js , , jQuery:

+5

email JavaScript?

email -, , script.

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

Source: https://habr.com/ru/post/1793034/


All Articles