As a rule I rarely if ever use setTimeout
because it’s so limited. So I don’t have a lot of experience with it. But I think you have a misreading of what that section is talking about.
I really have no idea what that "${varname}"
stuff is all about in the examples. If you are passing the variable as a parameter to the function, you use it inside the function the same as you’d use any variable passed to a function.
timer = setTimeout((si) => si.sendCommand("OFF"), seconds*1000, switchItem);
I wonder if the “${}” stuff is a mistake in the documentation markdown or something. @florian-h05 , do you have any ideas? I tried a bunch of stuff and can’t get anything reasonable to work using ${}
, whether I pass the variable as a parameter or not.
Beyond that, this approach seems awfully low level and you are reimplementing a bunch of stuff that is already provided to you or available elsewhere.
For example, the cache
would be a better choice than setting up your own map. For one thing when the rule gets unloaded all the timers get cancelled automatically. I know this works for OH Timers and think it works for setTimeout timers too. You don’t need to create a map to store the timers.
In fact, you don’t even need to create the timers at all. openHAB Rules Tools Announcements includes a TimerMgr that implements all of this for you. All of the code above would become:
var { TimerMgr } = require('openhab_rules_tools');
var tm = cache.private.get('timers', () => TimerMgr()); // create the timer manager if it doesn't already exist
function switchTimer(switchItem, seconds) {
tm.check(switchItem.name, seconds*1000, () => switchItem.sendCommand("OFF"));
}
If you want to share these timers between different rules (which isn’t always possible when using setTimeout) change cache.shared.get()
to use the shared cache with the timer manager.