我很难理解为什么下面的代码不能工作?
您可以在以下代码中看到以下代码:
`
HTML:
<input type="text" onkeyup="betterFunction(event)"/>
JS:
let newValue;
let counter = 0;
const getData = () => {
// dummy call to API and get Data
console.log("Fetching Data ..", newValue,counter++);
}
const debounce = function (fn, d) {
let timer;
return function () {
clearTimeout(timer);
timer = setTimeout(() => {
fn();
}, d);
}
}
const betterFunction = ({target:{value}}) => {
newValue=value;
debounce(getData, 2000); // **line 1**. placing this line of code debouncing does not happen
intermediate() // **line 2**. replacing this line of code with the above line debouncing works
}
const intermediate = debounce(getData, 2000);
`我了解到does函数返回另一个函数,它的作用类似于JavaScript中的闭包,但是为什么上面的第1行代码不能工作,但是第2行代码可以工作。
发布于 2020-08-07 12:25:26
debounce函数返回一个函数,当您将debounce调用为
debounce(getData, 2000);dobounce函数不需要返回函数。您只需要执行以下步骤就可以实现debounce函数:
timer是否未定义。如果没有,这意味着我们需要取消超时。之后的
setTimeout()来设置一个新的计时器,该setTimeout()在特定时间之后调用给定的函数。另外,timer不应该是局部变量,因为每当调用debounce函数时,都不希望它重置。
let counter = 0;
let newValue;
let timer;
const getData = () => {
console.log("Fetching Data ..", newValue, counter++);
}
const debounce = function(fn, d) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(fn, d);
}
const betterFunction = (e) => {
newValue = e.target.value;
debounce(getData, 2000);
}<input type="text" onkeyup="betterFunction(event)" />
如果您不想将timer声明为全局变量,并且希望从debounce函数返回一个函数,那么您需要最初调用debounce函数一次,每当keyup事件触发input元素时,就调用从debounce函数返回的函数,而不是调用debounce函数。
let counter = 0;
let newValue;
const getData = () => {
console.log('Fetching Data ..', newValue, counter++);
};
const debounce = function(fn, d) {
let timer;
return function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(fn, d);
};
};
const intermediate = debounce(getData, 2000);
const betterFunction = (e) => {
newValue = e.target.value;
intermediate();
};<input type="text" onkeyup="betterFunction(event)" />
发布于 2020-08-07 12:55:57
我希望你想要的:
let counter = 0;
// you need to define timer and newValue here first
let timer , newValue;
// defining input as varible for good usage better than usage in html
var input = document.querySelector("#inp");
const getData = () => {
// increment first better than in console :)
counter+=1;
console.log("Fetching Data .." , newValue , counter);
// as last step clear timer for next timeout
clearTimeout(timer);
}
// givin value direct to timer directlly worked better than return
const debounce = function (fn, d) {
timer = setTimeout(fn, d);
}
const betterFunction = () => {
// newvalue must equal input value
newValue = input.value;
// and then calling debounce as last step
debounce(getData, 2000);
}
// here giving onkeyup event to input for getting values and start working :)
input.onkeyup = betterFunction;https://stackoverflow.com/questions/63301553
复制相似问题