Skip to content

Instantly share code, notes, and snippets.

View PhilipWee's full-sized avatar

Philip Andrew Wee De Wang PhilipWee

View GitHub Profile
function useDebounce<Func>(func: Func, delay) {
const [timer, setTimer] = useState(); //Create timer state
const debouncedFunction = ((...args) => {
const newTimer = setTimeout(() => {
func(...args);
}, delay);
clearTimeout(timer); //Cancel previous timers
setTimer(newTimer); //Save latest timer
}) as Func;
import { useState } from "react";
function useDebounce<Func>(func: Func, delay) {
const [timer, setTimer] = useState(); //Create timer state
const debouncedFunction: Func = (...args) => {
const newTimer = setTimeout(() => {
func(...args);
}, delay);
clearTimeout(timer); //Cancel previous timers
import { useState } from "react";
function useDebounce(func, delay) {
const [timer, setTimer] = useState(); //Create timer state
const debouncedFunction = (...args) => {
const newTimer = setTimeout(() => {
func(...args);
}, delay);
clearTimeout(timer); //Cancel previous timers
function helloWorld() {
console.log("Hello World!");
}
const debouncedHelloWorld = useDebounce(helloWorld, 1000);
debouncedHelloWorld();
setTimeout(() => {
debouncedHelloWorld();
}, 500);
const debouncedHelloWorld = useDebounce(helloWorld, 1000);
debouncedHelloWorld();
setTimeout(() => {
debouncedHelloWorld();
}, 500);
//@ts-nocheck (We will handle the typescript later)
function useDebounce(func, delay) {
const debouncedFunction = (...args) => {
setTimeout(() => {
func(...args)
}, delay);
};
return debouncedFunction;
}
//@ts-nocheck (We will handle the typescript later)
function useDebounce(func, delay) {
const debouncedFunction = (...args) => {
setTimeout(() => {
console.log("This runs after (delay) ms");
}, delay);
};
return debouncedFunction;
}
//@ts-nocheck (We will handle the typescript later)
function useDebounce(func) {
const debouncedFunction = (...args) => {}
return debouncedFunction
}
//@ts-nocheck (We will handle the typescript later)
function useDebounce(func) {
return func
}
@PhilipWee
PhilipWee / debounce-hook.ts
Last active June 19, 2024 05:54
A simple typescript hook for debouncing functions
import { useRef, useEffect } from "react";
type Timer = ReturnType<typeof setTimeout>;
type SomeFunction = (...args: any[]) => void;
/**
*
* @param func The original, non debounced function (You can pass any number of args to it)
* @param delay The delay (in ms) for the function to return
* @returns The debounced function, which will run only if the debounced function has not been called in the last (delay) ms
*/