阻止执行回调直到输入停止 [英] Preventing a callback from executing until input stops

查看:142
本文介绍了阻止执行回调直到输入停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果未按任何键,则触发AJAX调用的计时器。如果按下某个键,则中止最后一个计时器并添加一个新计时器。这就是我想做但却未能成功的事情。这是我的代码:

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);
}


推荐答案

这听起来像你是要求辩护者。术语来自电子产品。这是一种防止多个事件在某个时间阈值内触发的方法。您可以使用以下函数创建一个新函数,只有在自上次事件后已经过了一定时间后才会调用该函数。

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));

给予 debounce 的回调不会只要点击事件继续触发就执行。

The callback given to debounce won't execute as long as click events keep firing.

优秀的 Underscore.js 库包含等效函数,并且至少有一些jQuery插件:

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/

这篇关于阻止执行回调直到输入停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆