用于调用ajax的Javascript时间计数器

用于调用ajax的Javascript时间计数器,javascript,jquery,html,ajax,Javascript,Jquery,Html,Ajax,我有许多不同的表单元素。当任何表单元素的值发生更改时,我需要在更改500毫秒后进行ajax调用 但是,如果另一个表单元素的值发生更改,那么我希望将计时器重置为500ms,从而避免多个Ajax请求在彼此500ms内发生一系列更改 是否有JavaScript或jQuery解决方案可以满足此需求?以下是一些代码,演示了您所寻找的原则: // Keeps track of the timer id in a scope that is outside of the event function // T

我有许多不同的表单元素。当任何表单元素的值发生更改时,我需要在更改500毫秒后进行ajax调用

但是,如果另一个表单元素的值发生更改,那么我希望将计时器重置为500ms,从而避免多个Ajax请求在彼此500ms内发生一系列更改


是否有JavaScript或jQuery解决方案可以满足此需求?

以下是一些代码,演示了您所寻找的原则:

// Keeps track of the timer id in a scope that is outside of the event function
// The variable will remain in memory and available to the next event call
var myTimer;

// Detect changes on keyup.
$('.textbox').on('keyup', function () {
    console.log('keyup');
    setMyTimer(500);
});
// Detect on change.
$('select').on('change', function () {
    console.log('change');
    setMyTimer(1000);
});

function setMyTimer(timerDelay) {
    // if myTimer has a value, then we should clear the timer. This stops us
    // from queuing multiple timers
    if (myTimer) {
        console.log('clear tiemout');
        clearTimeout(myTimer);
    }

    // Set the timer. It will be cleared if there is another handled 'keyup' 
    // event sooner than the timerDelay parameter
    myTimer = setTimeout(function () {
        console.log('Ajax stuff');
        // ajax stuff
    }, timerDelay);
};
在生产中使用之前,请删除
console.log
代码

请参见此工作演示:


请先尝试自己,如果您已经尝试了显示您的代码,我更改了答案,以显示将此代码用于不同元素上的多种事件类型的适用性。