setInterval() 是否重新评估函数的内容?

Does setInterval() re-evaluates the content of the function?

我正在写一个业余 SPA,基于 Vue(特别是 Quasar 框架)。

此应用程序,在 mounted() 中,连接到 MQTT 代理以获取一些信息(MQTT 在这里无关紧要 - 它可能是 API 使用 fetch() 调用,重点是结果以 JS 异步方式“一段时间后”可用)。此信息存储在 this.results.

我在某些组件中使用 this.results,内容按预期显示,并根据预期更新新结果(即 this.results 中的更改)。

因为这是家庭监控程序的前端,我还想显示最后一次获取结果的时间,如果我一段时间没有得到新结果则发出警报(这表明监控后端本身坠毁)。我去了:

mounted() {
    // connect to the MQTT broker = new results will come. That could be a setInterval fetch()
    this.client = mqtt.connect("mqtt://mqtt.swtk.info:1884");
    this.client.on("connect", this.mqttConnect);
    this.client.on("message", this.mqttMessage);
    // check every 900 ms for the last time I got the results, and set a variable for the elapsed time
    setInterval(
      function() {
        console.log(this.results)
        this.timeSinceLastRun = moment().unix() - moment(this.results.when).unix()
      },
      900
    )
  }

这是我连续(每秒)在控制台上收到的消息:

同时,this.results 定义:不仅来自 this.results 的内容在组件中正确显示,而且在查看 DevTool 时Vue 选项卡,我 我看到了:

看起来 setInterval() 函数中的 this.result 只评估了一次并且是 undefined - 这很好,因为当时还没有收到,但是将很快设置(在获得第一个结果后)。

不应该在每次 900 毫秒的函数调用中按“当前”使用它的值吗?

尝试像这样使用箭头函数() => {}

setInterval(
      () => {
        console.log(this.results)
        this.timeSinceLastRun = moment().unix() - moment(this.results.when).unix()
      },
      900
    )