Функция
в React, которая позволяет задержать выполнение функции или блока кода на указанное количество миллисекунд. Вот несколько методов, связанных с использованием setTimeoutв React:
-
Базовое использование:
setTimeout(() => { // Code to be executed after the specified delay }, delayInMilliseconds); -
Очистка тайм-аута:
const timeoutId = setTimeout(() => { // Code to be executed after the specified delay }, delayInMilliseconds); // To clear the timeout before it executes clearTimeout(timeoutId); -
Использование
setStateсsetTimeout:setTimeout(() => { setState({ /* Updated state */ }); }, delayInMilliseconds); -
Использование
useEffectсsetTimeout:useEffect(() => { const timeoutId = setTimeout(() => { // Code to be executed after the specified delay }, delayInMilliseconds); // Clear the timeout on component unmount return () => clearTimeout(timeoutId); }, []); -
Использование
setTimeoutс асинхронными функциями:async function fetchData() { await new Promise(resolve => setTimeout(resolve, delayInMilliseconds)); // Code to be executed after the specified delay }