Ahh, you closure!!

Vaibhav Rai
2 min readMar 19, 2024

--

We know the importance of closure in javascript, and one of the best examples is denouncing, where the user inputs some values, and till the typing is not completed the timeout will be cleared, and a particular callback will not be called.

I came across a unique situation I was iterating over all the coordinates and drawing the points one by one using the requesting window requestanimationframe but you see then the center of the map view is not aligned with the last coordinate which was added.

To solve this I had the idea to center the view after every 3 seconds

The first thing that came to my mind was debounced, but what I missed is that in debounce we clear the timeout if input keeps coming, here if I use the same logic then debounced will be called at the end of the iteration means view will at the starting position and the moment iteration reached the last coordinate, the view will jump to the end of the route or say last coordinate.

To solve this I created a util function called inInterval

  let t;
function inInterval (callback, point) {
if (t) {
return;
}
t = setTimeout(() => {
callback(point);
clearTimeout(t)
t = undefined;
}, 4000)
}

The logic was to not clear the timeout like debounce instead use it to check if setTimeout has already been executed, if it is then clear the timeout, if it's not then simply return the function.

The problem was solved!

Later we can add the animation to soothe the view flickering but inInterval delivered what we demanded.

(As a paragliding pilot myself and a Frontend developer, the purpose of this feature is to let the paragliding pilot upload their log file and visualize the flight with the elevation)

--

--

No responses yet