Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feature] useTimeout 是否可以考虑 return timer #1615

Closed
asyncguo opened this issue May 12, 2022 · 4 comments · Fixed by #1616
Closed

[feature] useTimeout 是否可以考虑 return timer #1615

asyncguo opened this issue May 12, 2022 · 4 comments · Fixed by #1616

Comments

@asyncguo
Copy link

期望 useTimeout 返回 timer,方便调用者可以手动取消定时器

function useTimeout(fn: () => void, delay: number | undefined): void {
  const fnRef = useLatest(fn);

  useEffect(() => {
    const timer = setTimeout(() => {
      fnRef.current();
    }, delay);
    return () => {
      clearTimeout(timer);
    };
  }, [delay]);
  
  // return 定时器的标识符
  return {
    timer
  }
}
@hchlq
Copy link
Collaborator

hchlq commented May 12, 2022

我觉得可以加一个取消定时器的返回函数,你觉得呢 @brickspert

@brickspert
Copy link
Collaborator

  1. 这里如果把 delay 改成 undefined 就可以暂停当前的 timer
  2. 增加一个 clear 函数也可以。 @hchlq

@hchlq
Copy link
Collaborator

hchlq commented May 12, 2022

如果把 delay 改成 undefined 确实可以,不过我觉得增加一个clear函数更好一点
原因是:

  1. 如果要更改 delayundefined ,调用者需要维护一个state去更改,感觉不是很有必要
  2. 返回一个clear函数更加符合直觉,调用者直接调用清理定时器即可

@crazylxr
Copy link
Collaborator

如果把 delay 改成 undefined 确实可以,不过我觉得增加一个clear函数更好一点 原因是:

  1. 如果要更改 delayundefined ,调用者需要维护一个state去更改,感觉不是很有必要
  2. 返回一个clear函数更加符合直觉,调用者直接调用清理定时器即可

同意第二点,第一点不一定,因为取消的时候往往是依赖于其他的 state 去取消的,大多数情况是不需要多声明一个状态的。

不过最终建议还是 加一个 clear。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants