DEV Community

technikhil314
technikhil314

Posted on

2 2

Debounce and throttle simplified

I was trying to create my own implementation of debounce and throttle. Yes just for fun.
and I came up with very simplified implementation that anyone can follow just by taking a look at the code.

You can play with the demo here

Hope you like it.

Throttle

function throttle(fun, timeduration) {
    let shouldCall = true;
    return (...args) => {
        if (shouldCall) {
            shouldCall = false;
            fun(...args);
            setTimeout(() => {
                shouldCall = true;
            }, timeduration)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Debounce

function debounce(fun, timeduration) {
    let lastTimeoutId = 0
    return (...args) => {
        if (lastTimeoutId) {
            clearTimeout(lastTimeoutId);
        }
        lastTimeoutId = setTimeout(() => {
            fun(...args);
        }, timeduration)
    }
}
Enter fullscreen mode Exit fullscreen mode

How to use it

function showValue(val) {
    console.log(val)
}

const throttleInput = throttle(showValue, 500);

const debouncedInput = debounce(showValue, 500);
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay