Saturday, 31 December 2016

internet explorer - Passing a Javascript function as an argument in IE




I am using a Javascript function do_when to keep evaluating another function and perform an action once it returns true. I found the function here: javascript, wait for something to be true then run action



Here is the do_when function:



function do_when(predicate, action, timeout_step) {
if (predicate()) {
action();
} else {
setTimeout(do_when, timeout_step, predicate, action, timeout_step);

}
}


I am using it to call a jQuery function:



do_when(function() {return tabledrawn;},
function() {$("#mytable tbody tr td").first().click();},
100);



Everything works fine in Firefox and Chrome, but IE9 (and earlier) fails. Specifically, I get an "Object Expected" error when do_when is called from the setTimeout function.



When I do a debug, the predicate and action arguments correctly show up as function objects when do_when is initially called, but when it is called again from the setTimeout function they both show up as undefined. It appears I am not supplying the arguments to setTimeout the way IE wants to see them. Is there a proper way in IE to pass a function object and its parameters as arguments?



EDIT:
Per SLaks suggestions I changed do_when to the following:



function do_when(predicate, action, timeout_step) {
if (predicate()) {
action();

} else {
setTimeout(function () {
do_when(predicate, action, timeout_step);
},
timeout_step);
}
}


Which fixes my problem.



Answer



You're passing additional arguments to setTimeout, and you're expecting them to be passed to your function.



That's a non-standard Mozilla-only feature.



Instead, you need to pass an anonymous function to setTimeout, and call your function with whatever arguments you want inside of it.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...