我看到下面的代码片段在每次用户更改后验证输入字段,但在实际开始验证之前等待用户不活动的1.5秒:
files_to_remove = [f for f in temp_list if os.path.exists(f)]
for f in files_to_remove:
os.remove(f)
log.info("Files removed [%s]", files_to_remove)
我的问题不是关于输入验证,而是关于超时机制。我试图推广延迟函数,使其适用于任意函数:
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
}
关键是你的JavaScript中有几个计时器,例如:
function delayedFunction(timer, func,delayInMilliseconds)
{
clearTimeout(timer);
timer = setTimeout(func, delayInMilliseconds);
}
如果您传递相同的计时器,延迟功能将清除(重置)正确的计时器,然后使用setTimeout函数再次设置它。
但是,这不起作用,因为计时器对象以逐个值的方式传递(discussion here),导致局部变量计时器被更改,但不是实际的inputTimer。
如何修复此方法?
答案 0 :(得分:2)
您可以使用类似
的内容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);