# Problem with stopping setTimeout

**URL:** <https://community.openhab.org/t/problem-with-stopping-settimeout/102180>\
**Category:** Scripts & Rules\
**Tags:** jsr223, javascript\
**Created:** [July 11, 2020, 11:52pm UTC](https://community.openhab.org/t/problem-with-stopping-settimeout/102180 "2020-07-11T23:52:34Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![khazzir](https://community.openhab.org/letter_avatar_proxy/v4/letter/k/57b2e6/32.png) [@khazzir](https://community.openhab.org/u/khazzir)\
**Post date:** [July 11, 2020, 11:52pm UTC](https://community.openhab.org/t/problem-with-stopping-settimeout/102180/1 "2020-07-11T23:52:34Z")

</div>

Hello,

I’m trying to run first Javascript rules with my OpenHab. I am running version 2.5.

Below are my two rules used for controlling lighting by presence detectors. I already know how to turn light on/off with presence detector but I am struggling with script which will turn the light OFF only when presence in the room will be OFF for “X” minutes. I have created setTimeout function and it turns light OFF with delay but I do not know how to exit this setTimeout function when the presence will again change to ON while counting already started.

Below is my script, any hints for beginner?

> (Java.type(“java.lang.System”).getenv(“OPENHAB\_CONF”)+‘/automation/lib/javascript/core/rules.js’);
> 
> var me = “HTTPRequestExamples.js”;  
> logInfo(“################# “+me+” ##################”);
> 
> JSRule({  
> name: “F\_LgtPscJadalnia\_ON”,  
> description: “LgtTurnOn”,  
> triggers: [  
> ItemStateChangeTrigger(“PscJadalnia”, “OFF”, “ON”, “ZmianaStanu”)
> 
> ```
> ],
> execute: function(){
>   
> var LGT = getItem("Lgt_TV")
> 
> sendCommand(LGT, "ON");
> }
> }
> 
> ```
> 
> );
> 
> JSRule({  
> name: “F\_LgtPscJadalnia\_OFF”,  
> description: “Testowa funkcja sterowania oświetleniem”,  
> triggers: [  
> ItemStateChangeTrigger(“PscJadalnia”, “ON”, “OFF”, “ZmianaStanu”)
> 
> ```
> ],
> 
> ```
> 
> execute: function( module, input){
> 
> ```
> var LGT = getItem("Lgt_TV")
> var PSC = getItem("PscJadalnia")
>   
>   
> logInfo( "Oświetlenie wyłączy się za 5 sekund");
> var t = setTimeout(function(){
> sendCommand(LGT, "OFF");
> if (PSC == "ON") function (){
> clearTimeout(t);
> }
> }, 5000);
> 
> ```
> 
> }
> 
> });

---

<div class="post-metadata">

**Author:** ![5iver](https://community.openhab.org/user_avatar/community.openhab.org/5iver/32/21201_2.png) [@5iver](https://community.openhab.org/u/5iver)\
**Post date:** [July 12, 2020, 2:28am UTC](https://community.openhab.org/t/problem-with-stopping-settimeout/102180/2 "2020-07-12T02:28:14Z")

</div>

> [@khazzir](#):
>
> Below is my script, any hints for beginner?

Use Jython?! 😜

> [@khazzir](#):
>
> I have created setTimeout function and it turns light OFF with delay but I do not know how to exit this setTimeout function when the presence will again change to ON while counting already started.

I would use core.actions.js to import ScriptExecution, and then use ScriptExecution.createTimer. You may want to look at the [JS Timer example](https://openhab-scripters.github.io/openhab-helper-libraries/Examples/Timer%20Example.html). As a basic rule, whenever possible, use Java or OH classes, interfaces and methods rather than what is available natively in your preferred scripting language.

---

<div class="post-metadata">

**Author:** ![tose](https://community.openhab.org/letter_avatar_proxy/v4/letter/t/ecc23a/32.png) [@tose](https://community.openhab.org/u/tose)\
**Post date:** [July 12, 2020, 9:41am UTC](https://community.openhab.org/t/problem-with-stopping-settimeout/102180/3 "2020-07-12T09:41:45Z")

</div>

Hi Robert,

it’s from my mobil and I hope it’s not to much typos.  
This should solve your task.

```auto
JSRule({
name: “F_LgtPscJadalnia_ON/OFF”,
description: “LgtTurnOnAndOff”,
triggers: [
  ItemStateChangeTrigger(“PscJadalnia”)
], 
execute: function( module, input){
  var LGT = getItem("Lgt_TV");
  var PSC = getItem("PscJadalnia");
  var t = null;

  var lightOFF_delayed = function() {
    if (PSC.state == "ON") sendCommand(LGT, "OFF");
    t = null;
  } 
  
  
  logInfo( "Oświetlenie wyłączy się za 5 sekund");
  if (PSC.state == ON) {
    if (LGT.state == OFF) sendCommand(LGT, "ON");
    if (t != null) {
      t.cancel()
      t = null;
    }

    if (PSC.state == OFF) {
      t = setTimeout(lightOFF_delayed, 5000);
    }
}

});

```

---

<div class="post-metadata">

**Author:** ![khazzir](https://community.openhab.org/letter_avatar_proxy/v4/letter/k/57b2e6/32.png) [@khazzir](https://community.openhab.org/u/khazzir)\
**Post date:** [July 12, 2020, 9:16pm UTC](https://community.openhab.org/t/problem-with-stopping-settimeout/102180/4 "2020-07-12T21:16:31Z")

</div>

Hi,

Great, thanks for help. Indeed there were some typos but I managed to clean them and finally function is working in way that I expect.

Below I attach full code for such function, maybe it will be useful for some another beginners 🙂

I’ve modified it to work with 0-100% dimmer instead of ON/OFF.

> JSRule({  
> name: “F\_LgtPscJadalnia\_ON/OFF”,  
> description: “LgtTurnOnAndOff by presence”,  
> triggers: [  
> ItemStateChangeTrigger(“PscJadalnia”)  
> ],  
> execute: function( module, input){  
> var LGT = getItem(“AktorDimJadalnia\_Dimmer1”);  
> var PSC = getItem(“PscJadalnia”);  
> var t = null;
> 
> var lightOFF\_delayed = function() {  
> if (PSC.state == “OFF”) sendCommand(LGT, “0”);
> 
> ```
> t = null;
> 
> ```
> 
> }
> 
> if (PSC.state == “ON”) {  
> if (LGT.state == “0”) sendCommand(LGT, “10”);  
> if (t != null) {  
> t.cancel()  
> t = null;  
> }}
> 
> if (PSC.state == “OFF”) {   
> t = setTimeout(lightOFF\_delayed, 1000000);  
> }
> 
> }   
> });

---

<div class="post-metadata">

**Author:** ![rickberon](https://community.openhab.org/letter_avatar_proxy/v4/letter/r/7ab992/32.png) [@rickberon](https://community.openhab.org/u/rickberon)\
**Post date:** [July 26, 2022, 7:42am UTC](https://community.openhab.org/t/problem-with-stopping-settimeout/102180/5 "2022-07-26T07:42:31Z")

</div>

setTimeout() and setInterval() functions allow you to execute a piece of JavaScript code/function at a certain point in the future. setInterval repeats the call, setTimeout only runs it once.

[setTimeout](http://net-informations.com/js/progs/delay.htm)(expression, timeout); runs the code/function once after the timeout. It is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout(). If you want something to happen one time after some seconds Then use setTimeout… because it only executes one time when the interval is reached.

```auto
setTimeout(function() {
  console.log('Wait 3 seconds and I appear just once');
}, 3000);

```

setInterval(expression, timeout); runs the code/function repeatedly, with the length of the timeout between each repeat. It is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval(). If you want to loop code for animations or clocks Then use setInterval.

```auto
setInterval(function() {
  console.log('Every 3 seconds I appear on your console');
}, 3000)

```
