JavaScript 函数延迟执行另一个函数

A JavaScript function that executes another function with a delay

我看到下面的代码片段在每次用户更改后验证输入字段,但它会等待 1、5 秒的用户不活动,然后才会真正开始验证:

var timer;

var inputElement = document.getElementById("nameInput");
inputElement.oninput = function()
{
    delayedInputValidation(validateInput, 1500);
};

function delayedInputValidation(func, delayInMilliseconds)
{
    clearTimeout(timer);

    timer = setTimeout(func, delayInMilliseconds);
}

function validateInput()
{
    ... //stuff here
}

我的问题不是关于输入验证,而是关于超时机制。我试图概括延迟函数以使其适用于任意函数:

function delayedFunction(timer, func,delayInMilliseconds)
{
    clearTimeout(timer);

    timer = setTimeout(func, delayInMilliseconds);
}

重点是你的 JavaScript 中有多个计时器,例如:

var inputTimer;
var otherTimer;
...

如果您传递同一个计时器,延迟函数将清除(重置)正确的计时器,然后使用 setTimeout 函数再次设置它。

然而,这不起作用,因为timer对象是以按值引用的方式传递的(discussion here),导致局部变量timer被改变,而不是实际的inputTimer。

如何修复此方法?

你可以使用像

这样的东西
var timers = {};
function delayedFunction(timer, func, delayInMilliseconds) {
    clearTimeout(timers[timer]);
    timers[timer] = setTimeout(func, delayInMilliseconds);
}
delayedFunction('inputTimer', func1, delay1);
delayedFunction('otherTimer', func2, delay2);

或者像这样:

var timers = [],
    inputTimer = 0,
    otherTimer = 1;
function delayedFunction(timer, func, delayInMilliseconds) {
    clearTimeout(timers[timer]);
    timers[timer] = setTimeout(func, delayInMilliseconds);
}
delayedFunction(inputTimer, func1, delay1);
delayedFunction(otherTimer, func2, delay2);