Skip to content

Instantly share code, notes, and snippets.

@NikaBuligini
Created February 10, 2020 16:00
Show Gist options
  • Select an option

  • Save NikaBuligini/7bcd13b5170bce20931ee4b03c946edd to your computer and use it in GitHub Desktop.

Select an option

Save NikaBuligini/7bcd13b5170bce20931ee4b03c946edd to your computer and use it in GitHub Desktop.
import React from 'react';
export function useInterval(callback, delay) {
const savedCallback = React.useRef();
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
React.useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
return undefined;
}, [delay]);
}
export function useTimeout(callback, delay) {
const savedCallback = React.useRef();
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
React.useEffect(() => {
function onTimeout() {
savedCallback.current();
}
if (delay !== null) {
const id = setTimeout(onTimeout, delay);
return () => clearTimeout(id);
}
return undefined;
}, [delay]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment