Skip to content
This repository was archived by the owner on Sep 1, 2024. It is now read-only.
Open
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
31 changes: 31 additions & 0 deletions react/useTimeout_en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
Ravikumar Daivajna

import React, { useEffect, useState, useRef } from "react";

export function useTimeout(callback: () => void, delay: number) {
const callbackRef = useRef(callback);
const timeoutRef = useRef(0);

useEffect(() => {
callbackRef.current = callback;
}, [callback]);

useEffect(() => {
// Clear the existing timer
clearTimeout(timeoutRef.current);

// Set a new timer with the updated delay
timeoutRef.current = setTimeout(() => callbackRef.current(), delay);

// Cleanup function to clear the timer on unmount or delay change
return () => clearTimeout(timeoutRef.current);
}, [delay]);
}

// if you want to try your code on the right panel
// remember to export App() component like below

export function App() {
useTimeout(() => { console.log("hello") }, 2000)
return <div>your app</div>
}