Solve the problem of using window. setTimeout () & amp; window. setInterval () and passing parameters! When using JScript, we sometimes need to execute a method at intervals, for example, to generate webpage UI animation effects. This is often the setInterval or setTimeout method, but since these two methods are the Timer threads simulated by the Script Host, our method through which we call cannot pass parameters for them.
Our common application scenarios are:
The Code is as follows:
Window. setTimeout ("delayRun ()", n );
Window. setInterval ("intervalRun ()", n );
Window. setTimeout (delayRun, n );
Window. setInterval (intervalRun, n );
Apparently, the parameter is forcibly called: window. setTimeout ("delayRun (param)", n );
The Code is as follows:
Window. setInterval ("intervalRun (param)", n );
Window. setTimeout (delayRun (param), n );
Window. setInterval (intervalRun (param), n );
All of them are incorrect. Because the method call in the string literals form must be a global variable (that is, the variable in the window object), and the call in the function pointer form is totally wrong, this regards the return value of the function as the parameter of the setTimeout/setInterval function, which is not what we want at all.
To solve this problem, we can use the anonymous function packaging method. In the following scenario, we do this:
The Code is as follows:
Function foo ()
{
Var param = 100;
Window. setInterval (function ()
{
IntervalRun (param );
},888 );
}
Function interalRun (times)
{
// Todo: depend on times parameter
}
In this way, you can no longer rely on global variables to pass parameters to the delayRun/intervalRun functions. After all, when there are more global variables on the page, it will bring huge puzzle to the development, debugging, and management of scripts.