Member-only story

Code Toolbox: 18 Practical JavaScript Functions

Beck Moulton
5 min readSep 28, 2024

--

This article will share some practical JavaScript code snippets that can help you improve code efficiency and simplify the development process. These codes cover common requirements such as URL handling, cache cleaning, retrieving CSS variables, and so on, making them very practical.

Function throttling 📡

/**Function throttling timer version*/     
function throttle(callback: Function, delay: number) {
let timer: number | null
return function () {
if (timer) return
const args = arguments //Using closures to save parameter arrays
timer = setTimeout(() => {
callback.apply(null, args)
timer = null
}, delay)
}
}

URL Code 💻

/**Encoding URL*/     
function encodeURL(url: string, isComponent = true): string {
return isComponent ? encodeURIComponent(url) : encodeURI(url)
} /**Decoding URL*/
function decodeURL(url: string, isComponent = true): string {
return isComponent ? decodeURIComponent(url) : decodeURI(url)
}

Using JavaScript to retrieve global CSS variables 📡

/**
* @description Using JS to retrieve global CSS variables
* @param CssVariableName variable name
* @returns {string} Variable value
*/
function getCssVariableValue(cssVariableName: string): string {
return getComputedStyle(document.documentElement).getPropertyValue(cssVariableName)
}

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

Responses (1)