Just define the function before the timeout
for(var i=0; nextFunction = aList[i];i++) {
var waitAndDoSomething = function(func) {
return function() { func.doSomething(); }
};
setTimeout(waitAndDoSomething(nextFunction),500*i);
}
Another Possible Answer
At minitect's suggestion, I started to think about other possible solutions. A solution that I feel comes out clean is to use bind
String.prototype.doSomething = function() { alert(this); } // Just for testing
var aList = ['one', 'two', 'three']; // Just for testing
for(var i=0;obj = aList[i];i++) {
setTimeout(obj.doSomething.bind(obj),500*i);
}
However, I am not sure how well this would work in the context of Razor Storm's question because I don't know what aList[i] would represent.
Does this answer the question
I also wonder if this is the intended behavior. It will not actually sleep after the execution but rather sets timing. This can be deceiving, but if we really want to execute a function and then sleep for a half a second before the next one our timing is off here. Instead I would use recursion:
String.prototype.doSomething = function() { alert(this); }
var aList = ['one', 'two', 'three'];
var doNextSomething = function(index) {
if (!index) { index = 0 }
if (nextObject = aList[index]) {
nextObject.doSomething();
setTimeout(doNextSomething, 500, index + 1);
}
};
doNextSomething();
Now, it will wait for 500 milliseconds after the function is executed (evident in a long running task).
I think that the answers posted were more what Razor Storm had it mind though.