Intervals and Function

I need help to turn on a buzzer at different intervals according to the variation in the input, I am currently simulating with a slider, but at the time of varying the interval is not deactivated, I attach the flow and function block

var msgHigh = {payload : 1};
var msgLow = {payload : 0};
var dato = {payload : 0};
var dato2 = {payload : 0};
function high(){
        node.send(msgHigh);
    }
function low(){
        setTimeout(function(){
            node.send(msgLow);
        },1000);
}
if(msg.payload=="0"){
        clearInterval(dato);
        clearInterval(dato2);
}else if(msg.payload=="1"){
        dato = {payload : setInterval(high,2000)};
        dato2 = {payload : setInterval(low,2000)};  
}else if(msg.payload=="2"){
        clearInterval(dato);
        clearInterval(dato2);
}else if(msg.payload=="3"){ 
        clearInterval(dato);
        clearInterval(dato2);
}

WhatsApp Image 2021-07-29 at 12.53.38

You need to save the timeout to a context variable and recover it each time the function node is triggered by an incoming msg. By saving a reference, you can cancel and recreate it easily.

Could you show me how?

Hmm, my live example uses a custom node.js module which would be hard to unpick.

Do you know how to get and set a context variable in a function node? If not start with the node-red docs and learn how to do that first.

When you have that, create a simple setInterval to output some text to the debug panel. and then add an if statement so that if the msg.payload = "kill", cancel the interval. Maybe something like this (untested):

let myInterval = context.get('myInterval') || null

if ( msg.payload === 'kill' ) {
   clearInterval(myInterval)
} else if ( msg.payload === 'create' ) {
   myInterval = setInterval( function() {
      node.warn('PING')
   }, 5000)
}

context.set('myInterval', myInterval)

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.