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() {

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图像没有加载


我不能构建vitejs + vue docker-compose







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