I'm currently wondering if there is a better solution than passing this scope to the lambda-function via the parameter 'e' and then passing it to 'funkyFunction' using call()-method
setInterval(function(e){e.funkyFunction.call(e)}, speed, this)
(Minor question aside: I'd been reading something about memory-leaks in javascript. How does the lambda-function affect my memory? Is it better to define it first like var i = function(e)... and then passing it as a parameter to setInterval?)
My situation may have been a bit different, but here's what I did:
var self = this;
setInterval(function() { self.func() }, 50);
My scenario was that my code was inside a class method and I needed to keep correct scope as I didn't want the 'this' binding to resolve to the current window.
eg. I wanted to run MyClass.animate from MyClass.init using setInterval so I put this scope-keep code into MyClass.init
You can use native bind function.
function Loop() {
this.name = 'some name for test';
setInterval( (function(){//wrap the function as object
//after bind, "this" is loop refference
console.log(this);
}).bind(this), 1000 );// bind the object to this (this is Loop refference)
}
var loop = new Loop();
paste this example in the console to see the result
What's wrong with simply relying on the outer-scope defined variable?
(function() {
var x = {};
setInterval(function() {
funkyFunction.call(x)
}, speed);
})();
I had the same question, but there seems to be no built in solution, so here is a quick workaround I punched together:
function setScopedInterval(func, millis, scope) {
return setInterval(function () {
func.apply(scope);
}, millis);
}
usage:
function MyClass() {
this.timer = null;
this.myFunc = function() { console.log('do some stuff'); };
this.run = function() {
this.timer = setScopedInterval(function () { this.myFunc(); }, 1000, this);
};
this.stop = function() { clearInterval(this.timer); };
}
var instance = new MyClass();
instance.run(); // will log to console every second
// until this line is called
instance.stop();
This only covers the use-case where you pass an actual function, not a string of code to be executed.
As for your question about memory leaks when using this functionality: it is not so much the problem with using setInterval as it is with anonymous functions in itself.
If you use a reference to an object inside a lambda, this reference will keep the referenced object in memory for as long as the anonymous function exists. I think the function is destroyed with a call to clearInterval.
I don't think there is any benefit from assigning the function to a variable first, on the contrary, it will create another variable containing a reference that will not be garbage collected as long as the anon func exists...
You may also have a look at the YUI Framework. It's fine for building applications and easy to learn.
YUI2: YAHOO.lang.later(when, scope, fn, args, periodic);
YUI3: Y.later(when, scope, fn, args, periodic);
UPDATE as example
Using YUI and jQuery (Do not forget enable $.noConflict())
var jQuerySelector = jQuery("div[class^='form-field-']");
jQuerySelector.hide();
jQuery(jQuerySelector[0]).show();
YAHOO.lang.later(5000, jQuery, function(jQuerySelector) {
if((!(this.index)) || (this.index == (jQuerySelector.length))) {
this.index = 0;
}
jQuerySelector.hide();
this(jQuerySelector[this.index++]).show();
}, jQuerySelector, true);
In short
1º parameter: 5000 on every 5000 miliseconds, 3º parameter (a function) will be executed
2º parameter: jQuery Object in which will be referenced by using this
3º parameter: function which will be executed. It receives as parameter either an array or an object passed as 4º parameter
5º parameter: true if true, executes continuously at supplied interval until canceled
see http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_later
UPDATE
No need for $.noConflict() because YUI does not use $ in any way.
There are two important distinctions to make.
1) Do you want a reference to the passed parameter so that the timeout function can track changes made to it, or do you want a clone of the passed parameter?
2) Do you want to be able to capture a reference to the timeout in case you want to cancel it? (Yes!)
// Normal setTimeout: retains a reference to `test` and returns the bad value
var test = 'test: good';
var timer = setTimeout(function() { console.log(test); }, 1000);
test = 'test: bad';
// Test2 receives a clone of `test2` and returns the good value, but does so right away, not on a timeout
var test2 = 'test2: good';
var timer2 = setTimeout((function() { console.log(test2); })(test2), 1000);
test2 = 'test2: bad';
// Test3 receives a clone of `test3` and returns the good value, but doesn't return a reference to the timeout, and can't be canceled
var test3 = 'test3: good';
var timer3 = function(test3) { setTimeout(function() { console.log(test3); }, 1000); }(test3);
test3 = 'test3: bad';
// Test4 receives a clone of `test4` and returns the good value, and correctly returns timeout reference
var test4 = 'test4: good';
var timer4 = function(test4) { return setTimeout(function() { console.log(test4); }, 1000); }(test4);
test4 = 'test4: bad';
// Test5 retains a reference to `test5` and returns the bad value
var test5 = 'test5: good';
var timer5 = setTimeout((function() { console.log(test5); }).bind(test5), 1000);
test5 = 'test5: bad';
// Did we capture references to the timeouts?
console.log(typeof timer);
console.log(typeof timer2);
console.log(typeof timer3);
console.log(typeof timer4);
console.log(typeof timer5);
Related
I know that this within setTimeout will correspond by default to window, so I have been using bind and passing it through to the self executing function, but when setTimeout finally runs (it's fine on the first run, called by TeaBot._manageTeaRound(), but it's not fine when self executing) this is undefined. Here's my code, where am I going wrong? (I have deleted some lines of code which might not be relevant). Thanks for your help :)
TeaBot.prototype._manageTeaRound = function(originalMessage, channel){
var self = this;
self.teaMaker = this._getUserById(originalMessage.user);
//now wait 3 minutes for people to send their order
self._runTimer(self,channel);
}
TeaBot.prototype._runTimer =function(self, channel) {
// do stuff
console.log(self.teaMaker.name); //undefined
var interval = self.interval,
teaMaker = self.teaMaker;
console.log("self.interval is " + self.interval);
if(interval === 0){
interval++;
self.interval = interval;
setTimeout(self._runTimer.bind(self, channel), 180000);
}else{
self.interval = 0;
}
}
This line is problematic:
setTimeout(self._runTimer.bind(self, channel), 180000);
Function TeaBot.prototype._runTimer expects self to be the first param - Function.prototype.bind() first param is context (function's this). Try use it like this:
setTimeout(self._runTimer.bind(self, self, channel), 180000);
Or leave context empty, becouse you are not using this at all:
setTimeout(self._runTimer.bind(undefined, self, channel), 180000);
This is because you are not using the value of this inside of _runTimer. You are binding a value this, but _runTimer couldn't care less.
_runTimer cares about its two parameters. The 1st being the context (self). The way your code is structured, there's no reason to use .bind here.
setTimeout(function(){
self._runTimer(self, channel);
}, 180000);
(Since you are passing the context (self) to the function, it makes no sense to have _runTimer be a part of TeaBot.prototype, since it needs a context passed to it.)
As an alternative, you can drop the self parameter, and have _runTimer reference this. That's when you would need to use .bind().
TeaBot.prototype._manageTeaRound = function(originalMessage, channel){
this.teaMaker = this._getUserById(originalMessage.user);
//now wait 3 minutes for people to send their order
this._runTimer(channel);
};
TeaBot.prototype._runTimer = function(channel) {
// do stuff
console.log(this.teaMaker.name);
var interval = this.interval,
teaMaker = this.teaMaker;
console.log("this.interval is " + this.interval);
if(interval === 0){
interval++;
this.interval = interval;
setTimeout(this._runTimer.bind(this, channel), 180000);
} else{
this.interval = 0;
}
};
the delay function:Delays a function for the given number of milliseconds, and then calls it with the arguments supplied.
is written from underscore js. annotated source:
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
for the delay function to work, why we need to use slice method and call (arguments,2), what does this part do?
Please correct me if im wrong. the delay function first return setTimeout to perform the delay, and the setTimeout function return func.apply(null,args) to pass on all of the information from one function to another? but what is "null" doing here?
when we call a function using delay, it says:
var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
=> 'logged later' // Appears after one second.
im not sure how the optional argument 'logged later' works here since im not sure how bind method works here either? can you please give me a simpler example?
setTimeout executes code in window context, so you have to take care to provide the correct reference for this in the callback function. _.bind does it for you.
var MyObject = function() {
this.myVariable = 'accessible';
this.myMethod = function(message) {
console.log((this === window));
console.log(message + this.myVariable);
}
}
var myObject = new MyObject();
// it will throw an error, because the this.myVariable isn't accessible
_.delay(myObject.myMethod, 1000, 'the correct scope is: ');
// this will be binded to the correct scope
_.delay(_.bind(myObject.myMethod, myObject), 1000, 'the correct scope is: ');
I am looking for a good technique to get away from what I am tempted to do: to set a global variable.
The first time someone runs a function by clicking a button it triggers an initial function to turn a few things into draggables. Later, if they click the button a second time I want to determine if the init function has been initialized, and if so to not call it again. I could easily do this by setting a global variable from the init function and then checking that variable from the click function, but I'm wondering how to do this without setting a global variable. I would really like an example of a way to do this.
You could add a property to the function:
function init() {
init.called = true;
}
init();
if(init.called) {
//stuff
}
While #Levi's answer ought to work just fine, I would like to present another option. You would over write the init function to do nothing once it has been called.
var init = function () {
// do the initializing
init = function() {
return false;
}
};
The function when called the first time will do the init. It will then immediately overwrite itself to return false the next time its called. The second time the function is called, the function body will only contain return false.
For more reading: http://www.ericfeminella.com/blog/2011/11/19/function-overwriting-in-javascript/
Why don't you just check to see if your draggables have a class of draggable on them?
if ($('.mydiv').is('.draggable')) {
//do something
}
Function.prototype.fired = false;
function myfunc() {
myfunc.fired = true;
// your stuff
};
console.log(myfunc.fired) // false
myfunc();
console.log(myfunc.fired) // true
What you could do is unhook the init function from the prototype.
var Obj = function () {
this.init = function () {
document.write("init called<br/>");
this.init = null;
}
}
var o = new Obj();
if (o.init) document.write("exists!<br/>");
o.init();
if (o.init) document.write("exists!<br/>");
o.init();
The first if will be true and print exists! but since the function removes itself, the second if will fail. In my example, I call the second init unconditionally just to show that nothing will happen, but of course you could call it only if it exists:
if (o.init) o.init();
http://jsfiddle.net/coreyog/Wd3Q2/
The correct approach is to use the Javascript Proxy APIs to trap the function calls using apply handler.
const initFun = (args) => {
console.log('args', args);
}
const init = new Proxy(initFun, {
apply(target, thisArg, args){
target.calls = target.calls ? target.calls + 1 : 1;
return target.apply(thisArg, args);
}
});
init('hi');
console.log(init.calls); // 1
init('hello');
console.log(init.calls); // 2
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
setTimeout and “this” in JavaScript
I am trying to put a timeout on an Object. With some test code (see below) I want to decrease the timerPos until it reaches 0. When I use the code below the first time timerInc() is called by startTimer(), it will reach 3 (as expected). When TimerInc() is called by the timeout i will receive 'undefined' for the timerPos variable. What am I doing wrong?
function start(){
var alert = new Alert(3);
alert.startTimer();
}
function Alert(timer) {
this.timerMinutes = timer;
this.timerPos = 0;
this.startTimer = function() {
this.timerPos = this.timerMinutes+1;
this.timerInc();
};
this.timerInc = function() {
if (this.timerPos > 0){
this.timerPos--;
// first time this function gets called timerPos is 3
// the second time when its called by the timeout it
// will be 'undefined'
setTimeout(this.timerInc,1000);
}
};
}
(using this.timerInc() in the timeout instead of this.timerInc does not work for me, neither does using quotes)
You need to bind the "this" variable to another one that you use explicitly since the value of "this" changes based on who is calling the function!
function Alert(timer) {
var that = this; // Store this Alert instance as "that".
this.timerMinutes = timer;
this.timerPos = 0;
// ...
this.timerInc = function() {
// Use the Alert instance "that", not whatever is bound to "this" at runtime.
if (that.timerPos > 0){
that.timerPos--;
setTimeout(that.timerInc, 1000);
}
};
}
The issue is that the setTimeout() function will call its function argument from global scope, not the scope of the enclosing object at the time it is registered. So in global scope the "this" variable is bound to the "global" object (likely the browser window).
You can verify like so:
setTimeout(function(){alert(this);}, 500); // => alerts "[object DOMWindow]"
First of all you should use prototype to declare the methods of your class Alert. And changing the scope of the function you're calling is gonna do the job:
function start(){
var alert = new Alert(3);
alert.startTimer();
}
function Alert(timer) {
this.timerMinutes = timer;
this.timerPos = 0;
}
Alert.prototype.startTimer = function() {
this.timerPos = this.timerMinutes+1;
this.timerInc();
};
Alert.prototype.timerInc = function() {
if (this.timerPos > 0){
this.timerPos--;
console.log(this.timerPos);
setTimeout(function(_this){_this.timerInc()},1000,this);
}
};
DEMO: http://jsfiddle.net/kmendes/HNYKa/1/
I'm writing a JavaSCript class that has a method that recursively calls itself.
Scheduler.prototype.updateTimer = function () {
document.write( this._currentTime );
this._currentTime -= 1000;
// recursively calls itself
this._updateUITimerHandler = window.setTimeout( arguments.callee , 1000 );
}
Property description:
_currentTime: the currentTime of the timer in miliseconds.
_updateUITimerHandler: stores the reference so can be used later with clearTimeout().
my problem is where I'm using recursion with setTimeout(). I know setTimeout() will accept some string to execute, or a reference to a function. since this function is method of an object, I don't know how to call it from outside. so I used the second format of setTimeout() and passed in a reference to the method itself. but it does not work.
Try this:-
Scheduler.prototype.startTimer = function() {
var self = this;
function updateTimer() {
this._currentTime -= 1000;
self.hTimer = window.setTimeout(updateTimer, 1000)
self.tick()
}
this.hTimer = window.setTimeout(updateTimer, 1000)
}
Scheduler.prototype.stopTimer = function() {
if (this.hTimer != null) window.clearTimeout(this.hTimer)
this.hTimer = null;
}
Scheduler.prototype.tick = function() {
//Do stuff on timer update
}
Well the first thing to say is that if you're calling setTimeout but not changing the interval, you should be using setInterval.
edit (update from comment): you can keep a reference from the closure if used as a class and setInterval/clearInterval don't require re-referencing.
edit2: it's been pointed out that you wrote callee which will work quite correctly and 100% unambiguously.
Out of completeness, this works:
function f()
{
alert('foo');
window.setTimeout(arguments.callee,5000);
}
f();
so I tried out document.write instead of alert and that is what appears to be the problem. doc.write is fraught with problems like this because of opening and closing the DOM for writing, so perhaps what you needed is to change the innerHTML of your target rather than doc.write
You could hold a pointer towards it...
/* ... */
var func = arguments.callee;
this._updateUITimerHandler = window.setTimeout(function() { func(); }, 1000);
/* ... */