I have a simpe object in javascript which has few methods..Two of them I want to periodicaly call with window.setTimeout functions. My current code looks like this.
var shakeResolver = function () {
var resolveTimeout;
console.log(this);
var context = this;
this.startShakeResolve = function () {
this.resolveTimeout = window.setTimeout(this.call(context.stopShakeResolve, context), 2000);
$(window)
.on('devicemotion', this.onDeviceMotion);
};
this.onDeviceMotion = function (event) {};
this.stopShakeResolve = function (context) {
this.resolveTimeout = window.setTimeout(context.startShakeResolve, settings.interval);
};
}
The problem is apparently in my misunderstanding how scopes are working, it looks like when calling the function from timeout, it is called from another context where it actually doesn't exist?
setTimeout, you're executing a function immediately and actually passing its return value (which happens to be undefined) as the function to call after the timeout. (Edit: that is, of course, assuming that your use ofthis.callinvokes the usualFunction.calland not your own variation.)this? Is it a function? How are you callingshakeResolver? To learn more aboutthis, have a look at developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/….