Chalarangelo / 30-seconds-of-code

Short code snippets for all your development needs

Home Page:https://30secondsofcode.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

variable inThrottle in snippets <throttle>

henrycjchen opened this issue · comments

commented

why there is a variable named "inThrottle" in snippets throttle?
"inThrottle" is true only at the begining, what is the purpose of it?

The inThrottle variable is used to initialize the throttling if I remember correctly - it's been a while since we wrote this snippet. I'll take a deeper look and figure it out, so that we can update the description, if possible as well.

const throttledResizeLog = throttle(function(evt) {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
  }, 250);

throttledResizeLog();
window.addEventListener(throttledResizeLog);
throttledResizeLog();

it's to prevent temporal race conditions between first evocation, and next loop racing each other and putting multiple timeouts, leading to a memory leak, event loop garbage, and overall awful time(heh)

lastFn = setTimeout(...)

if called multiple times, and a temporal race occurs, it would start leaking memory every evocation because when it goes to clear a Timeout it would not have the oldest evocation.

This function could be rewritten to be much smaller. Just keep in mind, if done wrong this will lead to a memory leak. Debouncing, lockouts, proper tracking of timeouts, etc. are needed to prevent it from operating multiple times each closure. This could probably be done by using an array of lastTimes and clearing it every successful evocation? IDK, I just took a quick look to see why it was there, and immediately saw the possibility of a mem leak. The event loop is wild.

"inThrottle" was init as undefined (Boolean as false).
while false, function will apply immediately and change this variable to true.
After wait few time( setTimeout Event loop), function will apply again.

commented

Thanks for explanation.