clearInterval在“ OFF”有效载荷上

时间:2019-12-16 00:32:16

标签: setinterval node-red clearinterval

我在使用一定的有效载荷实现clearInterval时遇到了新手困难。

  

if(msg.payload.state ===“ OFF”)

有效,但计时器不会停止。

在许多资源中,我看到了how to stop setInterval in JS in node-red..?node.js: how to use setInterval and clearInterval?clearInterval doesn't clearIntervalclearInterval On Image Slider Plugin

我确实有一个类似的函数“ dominos”,我曾经用来确保我正在解析“ OFF”有效载荷。 我已经包含了很多注释代码,以展示我尝试过的内容。对不起,一团糟!

我的语法有问题吗?

代码符合逻辑吗?

var input = msg.payload.state;
let timer = 0;

var red = {"state":"ON","brightness":255,"color":{"r":255,"g":0,"b":0}};
var green = {"state":"ON","brightness":255,"color":{"r":0,"g":255,"b":0}};


function xmas() {    // REPEATS!
    node.send({payload:red});
    setTimeout(function(){
        node.send({payload:green});
    }, 1500);
}
// repeat with 3 second interval
timer = setInterval(() => xmas(), 3000);
if (msg.payload.state === "OFF") {
    timer = clearInterval();
}

1 个答案:

答案 0 :(得分:1)

关于功能节点要记住的重要一点是,对于每个传入消息,其状态都将完全重置。这意味着let timer = 0;

总是会将计时器重置为零。

如果要在消息之间存储任何状态,则需要使用context

另外,使用clearInterval()的方式将永远无法工作,您需要将对timer对象的引用传递给此函数,以使其执行任何有用的操作。

下面的功能节点应该按照我的预期去做。

var red = {"state":"ON","brightness":255,"color":{"r":255,"g":0,"b":0}};
var green = {"state":"ON","brightness":255,"color":{"r":0,"g":255,"b":0}};


if (msg.payload.state != "OFF") {
   var timer = setInteval(()=>{
      node.send({payload: red});
      setTimeout(() => {
           node.send({payload: green});
      }, 1500);
   }, 3000);
   context.set("timer",timer);
} else {
   var timer = context.get("timer");
   clearInterval(timer);
}