0
Follow
0
View

js about a closure to prevent shaking doubts

dengmian1314 注册会员
2023-02-28 05:33

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > the first question is because the execution fangdou2(), the function of the code will be executed once, timeout has been defined as undefined, so if(timeout) the condition is not valid, setTimeout(callback, time) is executed directly, so the page will be automatically printed once when loaded.
-
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.

dongshengye77 注册会员
2023-02-28 05:33
< div class = "md_content_show e397 data - v - 3967" = "" >

thank you for your answer. I understand that the key problem is that in the callback function of addEventListener, I directly call foo as the callback parameter and pass the parameter, so I am directly executing the foo function, not as a function to listen for input changes at any time callback, so it will appear as soon as the load starts to print. The callback function for addEventListener must be an unexecuted function that requires an action to be executed in the callback function.

About the Author

Question Info

Publish Time
2023-02-28 05:33
Update Time
2023-02-28 05:33

Related Question

在Next Js图像没有加载

如何使MainActor可观察类坚持可编码协议?

我不能构建vitejs + vue docker-compose

使用apache-storm-2.2.1集群运行拓扑,有问题吗?

React-hot-toast自定义定位覆盖

c++:在main中从vector对象调用函数

我如何跳过第n个文件在Firestore?(复制)

将单选选项转换为vue.js中的按钮

不能让ShinyJS在闪亮DT禁用复选框

QT编译错误invalid conversion from 'unsigned char*' to 'const char*' [-fpermissive]