I'm just writing a function to carry out some admin tasks, like rebooting node-RED, shutting down the pi, etc, and have a countdown which when it reaches zero, the command is passed to an exec node to fulfill the request.
I want to also add a further feature - the ability to cancel the countdown (in case I've been too hasty!!). I was intending to add a further 'Cancel' inject node, and pick up it's msg.payload in the function node, and use that to stop the countdown.
However... I'm finding it difficult to actually stop the countDown function
once it has started!!
I understand that clearTimeout
is supposed to cancel setTimeout
, but I can't seem to get it to work (I don't think I'm implementing it correctly).
Any help would be appreciated as to how to do this.
function countDown(){
if(n > 0){
setTimeout(countDown,1000);
node.status({text:(text+" in "+n+" seconds")});
n--;
} else {
node.status({text:(text+" now!")});
node.send({"payload": cmd});
}
}
[{"id":"d9e67fbc.ddae3","type":"inject","z":"4487e413.bb781c","name":"System Shutdown","topic":"","payload":"shutdown","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":"","x":220,"y":1210,"wires":[["8c11f771.6cc238"]]},{"id":"b3dbd6a6.319368","type":"inject","z":"4487e413.bb781c","name":"System Reboot","topic":"","payload":"reboot","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":"","x":230,"y":1170,"wires":[["8c11f771.6cc238"]]},{"id":"87b651db.8fe59","type":"inject","z":"4487e413.bb781c","name":"Restart node-RED","topic":"","payload":"nrrestart","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":220,"y":1250,"wires":[["8c11f771.6cc238"]]},{"id":"8c11f771.6cc238","type":"function","z":"4487e413.bb781c","name":"Countdown","func":"var n = 10;\nsetTimeout(countDown,1000);\nconst ip = msg.payload;\nvar cmd;\nvar text;\n if (ip == \"reboot\"){\n cmd = \"sudo reboot\";\n text = \"System Reboot\";\n } else if (ip == \"shutdown\"){\n cmd = \"sudo shutdown\";\n text = \"System Shutdown\";\n } else if (ip == \"nrrestart\"){\n cmd = \"node-red-restart\";\n text = \"NR Restart\" \n } else if (ip == \"cancel\"){\n // stop the coundown\n }\n\nfunction countDown(){\n if(n > 0){\n setTimeout(countDown,1000);\n node.status({text:(text+\" in \"+n+\" seconds\")});\n n--;\n } else {\n node.status({text:(text+\" now!\")});\n node.send({\"payload\": cmd});\n }\n}","outputs":1,"noerr":0,"x":420,"y":1210,"wires":[["611156b9.772638"]]},{"id":"611156b9.772638","type":"debug","z":"4487e413.bb781c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":600,"y":1210,"wires":[]},{"id":"f2098287.c84cf","type":"inject","z":"4487e413.bb781c","name":"Cancel","topic":"","payload":"cancel","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":"","x":440,"y":1160,"wires":[["8c11f771.6cc238"]]}]