-
To avoid this, the initial value of timeout can be set to null, which determines if(timeout! == null) returns false, avoiding the problem of automatically executing the callback.
-
The second problem is that in the fangdou2() function, the closure function received callback and time arguments, but when listening for input events, it was passed con2 and 2000. This solves the timeout problem, but it doesn't fire the function properly. Consider passing con2 and 2000 as arguments to the closure function, rather than as arguments to the listener function. The modified code is as follows:
function fangdou2() {
let timeout = null;
return function(callback, time) {
if (timeout !== null) clearTimeout(timeout);
timeout = setTimeout(callback, time);
}
}
function con2() {
console.log('发起请求2');
}
const foo = fangdou2();
document.addEventListener('input', function() {
foo(con2, 2000);
});
This should trigger the function normally.