Restrict the number of times a function can be executed concurrently.

/**
* Restricts an async callback from being executed more than a fixed amount of times in a row.
*
* @param {Async Function} asyncCallback
* @param {Number} times numer of times allowed for the callback to be executed in a row
* @returns {Async Function} restricted callback
*/
export function restrictConcurrentTimes(asyncCallback, times = 1) {
let executed = 0
return async (...args) => {
if (executed >= times) {
return
}
try {
executed += 1
await asyncCallback(...args)
} finally {
executed -= 1
}
}
}

Usage

new IntersectionObserver(
restrictConcurrentTimes(async ([entry], observer) => {
if (entry.isIntersecting) {
await fetch('...')
}
}),
options
)
window.addEventListener(
'mousemove',
restrictConcurrentTimes(async () => {
await new Promise(r => setTimeout(r, 2000)) // or whatever
}, 2 /* concurrent executions */),
{ pasive: true }
)

--

--

--

I write all posts for my future self. Web Engineer at @PayPal, M.S. in Computer Science w/specialization in Computing Systems, B.Eng. in Computer Software.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

React: Custom Cursor (No Extra dependencies!)

Building a Budgeting React App with Semantic UI Bars

30 Day Typescript Type Challenge — Challenge 2

Frontend Weekly Digest #226 (6–12 September 2021)

How to Convert MSG to JPG in Node.JS

How to Update Table in SQL?

Fix Keycloak Script Upload Is Disabled. How to export / import / backup your realm configuration.

Difference between javascript object vs JSON object?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pablo Garcia

Pablo Garcia

I write all posts for my future self. Web Engineer at @PayPal, M.S. in Computer Science w/specialization in Computing Systems, B.Eng. in Computer Software.

More from Medium

Practical Pair Programming

Functional programming : Avoid Side Effects

An Overview of Cache & its Types

Spread vs Rest Parameter vs Argument object