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,