Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions snippets/javascript/function-utilities/throttle-function.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
title: Throttle Function
description: Ensures a function is only called at most once in a specified time interval. Useful for optimizing events like scrolling or resizing.
author: WizardOfDigits
tags: throttle,performance,optimization
---

```js
const throttle = (func, limit) => {
let inThrottle;
return (...args) => {
if (!inThrottle) {
func(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
};

// Usage:
// Ensures the function can only be called once every 1000 milliseconds
const logScroll = throttle(() => console.log("Scroll event triggered"), 1000);

// Attach to scroll event
window.addEventListener("scroll", logScroll);
```