Andreas Bergmaier wrote:
> Tuxedo schrieb:
>> How can a simple string parameter be passed between two functions while
>> inside a setInterval call? For example:
>>
>> function initialFunction(x){
>> alert(x);
>> setInterval('repeatingStuff(x)',5000);
>> }
>>
>> function repeatingStuff(x){
>> alert(x);
>> }
>> ...
>>
>> <a href="..." onclick="initialFunction('param_x');">stuff</a>
>>
>> But the error "x is not defined" results from ..Stuff(x) in
>> setInterval('repeatingStuff(x)',5000). How can the parameter between the
>> two functions be passed within the setInteval bit?
>
> x must be in the scope of the second function.
In the scope _chain_.
> Therefore, you should define repeatingStuff inside the initialFunction:
>
> function initialFunction(x){
> alert(x); ^
^--------------'
> function repeatingStuff(x){
^
> alert(x); |
^--------------'
> }
> setInterval(repeatingStuff,5000);
> }
>
> or shorter:
>
> function initialFunction(x){
> alert(x); ^
^--------------'
> setInterval( function(x){
> alert(x); ^
^------------'
> }, 5000);
> }
This does not work, because in the context of the function (referred by
`repeatingStuff'), `x' is bound to the inner function's argument `x' (which
is not passed a useful value from the DOM implementation anyway) and not to
that of the inner function's definition context. Please test before you
post, or clearly mark code as untested.
> You should pass a function to setIntervall/Timeout, instead of a code to
> be evaluated each time (slow & buggy).
The function code also will have to be evaluated each time. But it is true
that evaluating the string value as a Program is less efficient and more
error-prone than that.
> Another alternative is to use bind() or other functions, to return a
> function which calls repeatingStuff with the needed parameters:
>
> function repeatingStuff(){...}
> function initialFunction(x){
> alert(x);
> setInterval( repeatingStuff.bind(this, x), 5000);
> }
This works in implementations of ECMAScript 5.x or where you have a suitable
scripting framework that emulates Function.prototype.bind(), but it is
unnecessarily inefficient by comparison.
PointedEars
--
> If you get a bunch of authors […] that state the same "best practices"
> in any programming language, then you can bet who is wrong or right...
Not with javascript. Nonsense propagates like wildfire in this field.
-- Richard Cornford, comp.lang.javascript, 2011-11-14