javascript - Returning from setInterval in JavaScript/React.js
问题描述
I'm trying to return a value from my setInterval function. My code looks like that:
export const timeCounter = () => {
const date = "2018-08-12T18:45:00.000Z"; //this is just mocked data
const matchDate = new Date(date);
let dateToShow;
const showTime = () => {
const currentDate = new Date();
const distance = matchDate - currentDate;
return dateToShow = distance < 0 ? "FINISHED" : null;
};
const timer = setInterval(showTime, 1000);
console.log(timer) // here I'd like to see refreshing value (FINISHER or nothing)
};
What I'm trying to do is to run my interval every second with showTime function. What I need to return is just "FINISHED" or nothing. But console.log(timer) won't give refreshed status. Thanks for helping.
解决方案
setInterval
不会返回您期望的字符串 'FINISHED' 或 null,但它会返回唯一标识间隔的间隔 ID,因此您可以稍后通过调用将其删除clearInterval()
。此方法在 Window 和 Worker 接口上提供。
推荐阅读
- java - 当我尝试打开数据库存储写入器时,android studio 无法打开下一页或有时会显示“不断停止”消息
- sql - 在分析服务中处理时出错
- ssh - 合并 ssh 配置
- python-3.x - 如何从数据库中获取数据并分别在 django 的引导模式框(弹出)中显示?
- arrays - 通过散列键搜索散列数组及其在 Perl 中的排序
- php - 用户登录 MVC 框架后更改默认路由
- eclipse - 有没有办法为在 Eclipse 中有两个不同工具链的 2 个嵌套项目共享相同的文件目录?
- deep-linking - 当应用程序显示弹出视图时,无法使用动态链接(Firebase)转到 DetailViewcontroller
- android - 在 Scroll RecycleView 上加载下一篇文章时出现错误
- java - 为什么我不能在 java java.lang.Enum 泛型类型定义中重复出现?