I want to pass an object array to the setTimer function in Javascript.
setTimer("foo(object_array)",1000);
am getting error on this code.
**Note:**Sorry ! some correction in my question : Is it possible in setInterval() function.
Use an anonymous function instead of a string on the first parameter of the setTimeout or setInterval functions:
// assuming that object_array is available on this scope
setInterval(function () { foo(object_array); }, 1000);
Why it works:
When you define an inner function, it can refer to the variables present in their outer enclosing function even after their parent functions have already terminated.
This language feature is called closures.
If you pass a string as the first argument of these functions, the code will be executed internally using a call to the eval function, and doing this is not considered as a good practice.
Eval provides direct access to the JavaScript compiler and executes the code it's passed with the privileges of the caller, also using eval repeatedly/extensively (i.e. your setInterval function is a good example) will lead to performance issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With