setTimeout and clearTimeout as callback to hook programatically

Viewed 30

I want to create a function that return setTimeout as a callback to call it programmatically and a clearTimeout as a callback to cancel the setTimeout before it executes the internal callback if necessary, is it possible?

function useDelay(cb: () => void, delay: number) {
  const timer = () => setTimeout(cb, delay);
  const clearTimer = () => clearTimeout(timer());
  return [timer, clearTimer];
}
1 Answers

You we're executing the timer in the clearTimeout. It should take a reference instead.

function useDelay(cb = () => {}, delay = 2000) {
  let timerRef;
  const timer = () => {
    timerRef = setTimeout(cb, delay);
  }
  const clearTimer = () => clearTimeout(timerRef);
  return [timer, clearTimer];
}

const [timer, clearTimer] = useDelay(() => console.log('test'), 2000);

Related