In JS, whether it is setTimeout or setInterval, parameters cannot be included when using the function name as the call handle. In many cases, parameters must be included, next we will introduce the specific solution. In JS, whether it is setTimeout or setInterval, parameters cannot be included when using the function name as the call handle. In many cases, parameters must be included,
This requires a solution.
1. Use a string: The -- (defect) parameter cannot be periodically changed
SetInterval ("foo (id)", 1000 );
Ii. Anonymous function packaging (recommended)
The Code is as follows:
Window. setInterval (function ()
{
Foo (id );
},1000 );
In this way, the foo (id) function can be periodically executed and the variable id can be passed in;
3. Define a function that returns a function without Parameters
The Code is as follows:
Function foo (id)
{
Alert (id );
}
Function _ foo (id)
{
Return function ()
{
Foo (id );
}
}
Window. setInterval (_ foo (id), 1000 );
A function _ foo is defined here, which is used to receive a parameter and return a function without a parameter. An external function parameter is used inside the function to call it, no parameters are required.
In the window. setInterval function, _ foo (id) is used to return a function handle without parameters, thus implementing the function of passing parameters.
4. Modify setInterval
The Code is as follows:
Function foo (id)
{
Alert (id );
}
Var _ sto = setInterval;
Window. setInterval = function (callback, timeout, param)
{
Var args = Array. prototype. slice. call (arguments, 2 );
Var _ cb = function ()
{
Callback. apply (null, args );
}
_ Sto (_ cb, timeout );
}
Window. setInterval (hello, 3000, userName );
All the above methods are also suitable for setTimeout.