Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an Array object to the setInterval function

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.

like image 938
coderex Avatar asked Nov 30 '22 11:11

coderex


1 Answers

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.

like image 52
Christian C. Salvadó Avatar answered Dec 04 '22 07:12

Christian C. Salvadó