Here are two examples, one with a change node and JSONata and one with a function node.
[{"id":"f6d60f43.f99f28","type":"inject","z":"c74669a0.6a34f8","name":"true","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"d\":{\"running\":true}}","payloadType":"json","x":140,"y":4800,"wires":[["8137485b.2adc38","1ae2aea3.fb16f9"]]},{"id":"8137485b.2adc38","type":"change","z":"c74669a0.6a34f8","name":"","rules":[{"t":"set","p":"ontime","pt":"flow","to":"payload.d.running = true ? $millis() : $flowContext(\"ontime\")","tot":"jsonata"},{"t":"set","p":"result","pt":"msg","to":"payload.d.running = false ? ($millis()-$flowContext(\"ontime\"))/1000 ","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":360,"y":4820,"wires":[["32050b10.1fbba4"]]},{"id":"1ae2aea3.fb16f9","type":"function","z":"c74669a0.6a34f8","name":"","func":"let tt = msg.payload.d.running ; // this will return a Boolean value based on ON or OFF \n\n\n\n\nif(tt == true) {\n context.set(\"ontime\", new Date()); \n}else {\n \n msg.result= (new Date() - (context.get(\"ontime\") || 0))/1000 ;\n}\n return msg; \n","outputs":1,"noerr":0,"initialize":"","finalize":"","x":380,"y":4880,"wires":[["32050b10.1fbba4"]]},{"id":"231785df.d067ca","type":"inject","z":"c74669a0.6a34f8","name":"false","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"d\":{\"running\":false}}","payloadType":"json","x":140,"y":4860,"wires":[["8137485b.2adc38","1ae2aea3.fb16f9"]]},{"id":"32050b10.1fbba4","type":"debug","z":"c74669a0.6a34f8","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":580,"y":4820,"wires":[]}]