javascript - 我应该如何声明一个具有 setInterval 值的变量?

标签 javascript reactjs setinterval

我正在查看一个问题,有人用下面的代码回答了它,并在评论中有人说

I think instead of assigning undefined we should assign 0 to this.tm. As it's time interval and it should not be undefined.

constructor(props) {
    super(props);       

    this.tm; // With what value should this be declared?
}

timerInterval = () => {        
    this.tm = setInterval(() => {
            ...
    }, 1000);
}

render(){
    return(...)
}

所以这让我想知道,它应该声明什么值?从 undefined 更改为 0 有什么区别吗?

来自文档或类似内容的引用文献可以很好地解释它。我没找到。

最佳答案

所以,结合所有评论

  • 我不需要在构造函数中声明它,我可以正常使用 this.tm 。如果我声明它,这只是一种让代码更清晰的好习惯。
  • This answer对于为什么最好将其设置为 0 有正确的解释,但仅限于浏览器。如果是node环境,最好设置为null。

    On browsers, the handle is guaranteed to be a number that isn't equal to 0; therefore, 0 makes a handy flag value for "no timer set". (Other platforms may return other values; NodeJS's timer functions return an object, for instance.)

关于javascript - 我应该如何声明一个具有 setInterval 值的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524306/

相关文章:

javascript - 解释Javascript代码,填充到字符串的左侧或右侧

javascript - 如何在 Accordion 中切换类 "active"

javascript - ReactJS MobX 和 react-router v4 问题与 url 历史

JavaScript 每 15 分钟计算一个值并在午夜重置它

javascript - 使用 Angular 2 加载多个子组件

javascript - 提交表单后重定向页面 - Javascript

javascript - 外部 Javascript 在 react.js 中不起作用

android - AsyncStorage 数据在 Android 设备上的物理位置在哪里?

javascript - setInterval 的这种行为是否意味着 Javascript 中的多线程行为?

jquery - 如何使用 jQuery 使阴影闪烁?