A Modern Vanilla JavaScript Throttle To Replace Lodash
I'm using this function from You-Dont-Need-Lodash-Underscore^ydn^^ to throttle the color selection sliders for my OKLHC Color Picker to prevent performance issues:
JavaScript
var lastTime = 0;
return
var now = ;
};
}
const throttleUpdate =
document.
HTML
/>
0
Details
I'm making a Color Picker that uses "OKLCH" to choose the colors^picker^^. OKLCH is the name of a method for converting the values from the picker's sliders into the color itself. Traditional pickers use different methods (like "RGB" and "HSL"). The OKLCH method is nicer. Changing a slider changes the colors in a way that makes more intuitive sense^why^^.
I'm using four significant figures for the Chroma value. At that level, there's an individual value for every individual pixel on the slider. That, in turn, means that every littls movement of the slider causes a signal to be sent to update all the colors on the page. If you whip the slider back and forth it's more than the browser can handle and things bog down.
The fix is to add a "throttle" into the mix.
Throttling
Adding a throttle
uses sliders to control Lightness, Chroma, and Hue. There are several palettes on the page. All of which change when a slider is moved. It was immediately evident that using the default speed of the `change`` event listener caused problems. Things would bog down frequently.
The fix was to add this throttle into the mix:
JavaScript
When you wrap another function inside the `throttle`` it limits how much it's called based on the `timeFrame`` (which is in milliseconds). For example, check out this slider, and the three display values below it:
HTML
/>
0
0 0
JavaScript
const
document.. =
event..
}
const throttled1 =
const throttled2 =
document.
Footnotes
-
(id:picker)
I'm still working on it at the time of this post, but it's already one of the favorite things I've built. That's as much to do with the way I'm writing the code (which I think I'm going to call "YAGINP JS" for "You Ain't Gonna Need It Philosophy JS"). Bascially, it's a little set of functions that act as a library for manipulatinng the DOM. Combined with Neopoligen it's been a delight to work with.
-
(id:ydn)
From the page: Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers. However, when you are targeting modern browsers, you may find out that there are many methods which are already supported natively thanks to ECMAScript5 [ES5] and ECMAScript2015 [ES6]. If you want your project to require fewer dependencies, and you know your target browser clearly, then you may not need Lodash/Underscore.
-
(id:why)
References
-
I've always called them Significant Digits, but the main page uses the term Significant Figures. Who knew?