In JS, whether settimeout or setinterval, use the function name as the call handle can not take parameters, and in many cases must take parameters,
This needs to be solved in a way.
First, in the form of a string:--(defect) parameters can not be periodically changed
SetInterval ("foo (ID)", 1000);
Second, anonymous function packaging (recommended)
Window.setinterval (function ()
{
Foo (ID);
}, 1000);
This allows you to periodically execute the Foo (ID) function and pass the variable ID in;
Iii. defining functions that return parameterless functions
function foo (ID)
{
alert (ID);
}
function _foo (ID)
{
return function ()
{
Foo (ID);
}
}
Window.setinterval (_foo (ID), 1000);
This defines a function _foo, which receives a parameter and returns a function with no parameters, which uses the arguments of the external function inside the function to invoke it without using parameters.
In window. In the SetInterval function, the _foo (ID) is used to return a function handle with no parameters, thus enabling the function of parameter passing.
Iv. Modification of SetInterval
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 of the above methods are also suitable for settimeout. |
This article links http://www.cxybl.com/html/wyzz/JavaScript_Ajax/20130712/39060.html