The only problem with the anonymous function solution is one of scope.
This just bit me yesterday:
function processArray(arr) {
var i=0, len = arr.length;
for (i; i<len; i++) {
window.setTimeout(function() {
doSomething(arr[i]);
}, 500);
}
}
Looks like it should work, but every time doSomething gets called, the
parameter it receives is the final element in the array -- by the time
of the first invocation, i has already fallen out of the for loop and
been incremented to arr.length.
But you can rewrite this to make it work:
function processArray(arr) {
if (arr.length) {
window.setTimeout(function() {
doSomething(arr.shift());
processArray(arr); // warning, recursion alert!
}, 100);
}
}
This is just a hastily-hacked-together function; in real production
code you'd want to do something that didn't remove every item from the
array. ;)
On Jan 25, 1:30 pm, Ken Snyder <
kendsny...@gmail.com> wrote:
> // To pass params, use an anonymous function (best used on all browsers)
> window.setTimeout(function() {
> myFunc(param1, param2);
>
> }, ms);
>
> On Wed, Jan 25, 2012 at 11:27 AM, Michael Jones <
jmichaeljo...@gmail.com>wrote:
>
>
>
> > Agreed. The main problem with things like eval() (which keeps getting
> > autocorrected to veal() on my end, heh) is when you do something stupid™
> > with it, such as taking user input and passing it into eval'ed code. But if
> > you can control what goes into the string it's not so bad.
>
> > Either way, however, the issue still remains how do you pass an argument
> > to a function called by setTimeout on IE if it doesn't support passing the
> > params in separately? The string eval seems to be the only way.
>
> > --
>
> > No trees were knowingly harmed in any way during the production and
> > transmission of this message. However, a rather large number of electrons
> > were somewhat inconvenienced.
>
> > On Wednesday, January 25, 2012 at 11:17 AM, Ken Snyder wrote:
>
> > I agree that eval should not be used unless needed, but I think there are
> > a fair number of good uses.
>
> > Most JS libraries provide an easy way eval javascript that is returned in
> > script tags in an ajax response. Here is jQuery's that can be called
> > manually or is called automatically with certain jQuery.ajax options:
> > jQuery.globalEval <
http://api.jquery.com/jQuery.globalEval/>.
>
> > Some selector libraries like NWMatcher use eval() or new Function("...")
> > to compile selector logic.
>
> > Here is a good discussion: Why eval can be bad<
http://stackoverflow.com/questions/86513/why-is-using-javascript-eval...>
>
> > - Ken
> > Options:
http://groups.google.com/group/utahjs- Hide quoted text -
>
> - Show quoted text -