Read the statement by Michael Teeuw here.
Need help in Javascript for resetting module if user no longer interacts after x seconds.
-
I am using a Sonar module on Raspberry Pi to indicate whether someone is in front of the mirror or not. I use MMM-websocket to transfer this information to MagicMirror and it works correctly. Now, when there is nobody in front of the mirror for x seconds, I would like to call a function to reset the module. However, I got an issue on Javascript side:
Currently I have this function for resetting in my module:
userNoLongerInFrontSoReset: function(){ if (this.resetTimeout != null){ clearTimeout(this.resetTimeout); } this.resetTimeout = setTimeout(function(){ console.log("resetTimeout setTimeout"); this.myVar = null; this.myVar2 = null; this.myVar3 = null; this.sendNotification("PAGE_CHANGED", 0); this.updateDom(); }, 3000) }
I see from the console that
resetTimeout setTimeout
is being printed out from the code above, but then it got:Uncaught TypeError: this.sendNotification is not a function at myOwnModule.js:xxx
So
this
is the problem. All those variablesmyVar
, etc. are not being referred correctly as well as the functionsendNotification
. How can I set allmyVar
and callsendNotification
from the anonymous function in this case? Or is there a better way to do this?Thank you,
-
@jchariot
Change this;this.resetTimeout = setTimeout(function(){ ... this.sendNotification("PAGE_CHANGED", 0); this.updateDom(); ...
to this;
this.resetTimeout = setTimeout(()=>{ ... this.sendNotification("PAGE_CHANGED", 0); this.updateDom(); ...
Or this;
var module = this this.resetTimeout = setTimeout(function(){ ... module.sendNotification("PAGE_CHANGED", 0); module.updateDom(); ...
Inside of
function(){...}
,this
will be function itself, so you cannot accessthis
- referer to module - of upper level.
To avoid, you can use ES6 style anonymous function()=>{}
insteadfunction(){}
or assign priorthis
to another temporal object. -
@sean or
this.resetTimeout = setTimeout(function(){ ... this.sendNotification("PAGE_CHANGED", 0); this.updateDom(); ... }.bind(this));