Home > front end >  A struggle for a long time problem, about a satisfaction of js stabilization combined with closures,
A struggle for a long time problem, about a satisfaction of js stabilization combined with closures,

Time:12-09

//if you
The function calcTop (fn, delay) {
let timer=null;
The console. The log (timer);
Return the function () {
If (timer) {
ClearTimeout (timer);
}
The timer=setTimeout (fn, delay);
}
}

Window. The onscroll=calcTop (scrollTop, 1000);

Why the timer executed only once? Not just roll trigger if personal leave? For help,,,

CodePudding user response:

Rolling trigger calcTop function, calcTop using setTimeout timer to preserve the returned reference, every time calcTop function to perform, will first check the timer exists, if there is put before the imer, also is the timer clear (clearTimeout), so the fn setTimeout natural won't perform,

CodePudding user response:

reference 1st floor foreverpx response:
rolling trigger calcTop function, calcTop using setTimeout timer to preserve the returned reference, every time calcTop function to perform, will first check the timer exists, if there is put before the imer, timer is cleared (clearTimeout), so the fn setTimeout natural won't perform,

Ok, thank you, that the console. The log (timer) why only print a null, roll back no matter what all don't print again

CodePudding user response:

refer to the second floor ten years pinellia ぅ response:
Quote: refer to 1st floor foreverpx response:
rolling trigger calcTop function, calcTop using setTimeout timer to preserve the returned in reference, every time calcTop function to perform, will first check the timer exists, if there is put before the imer, also is the timer clear (clearTimeout), so the fn setTimeout natural won't perform,

Ok, thank you, that the console. The log (timer) why only print a null, roll back no matter what all don't print again

Because calcTop function returns a function, the function is assigned to the onscroll, when rolling is performed this function, rather than calcTop,

CodePudding user response:

reference 5 floor foreverpx reply:
Quote: refer to the second floor ten years pinellia ぅ response:
Quote: refer to 1st floor foreverpx response:
rolling trigger calcTop function, calcTop using setTimeout timer to preserve in returning to the reference, every time calcTop function to perform, will first check the timer exists, if there is put before the imer, also is the timer clear (clearTimeout), so the fn setTimeout natural won't perform,

Ok, thank you, that the console. The log (timer) why only print a null, roll back no matter what all don't print again

Because calcTop function returns a function, the function is assigned to the onscroll, when rolling is performed this function, rather than calcTop,

Ok, thank you bosses patient answer
  • Related