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:
Code:
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 );
Code:
Window. setinterval ("intervalrun (PARAM)", N );
Window. setTimeout (delayrun (PARAM), N );
Window. setinterval (intervalrun (PARAM), N );
The above methods are all incorrect because Param must be a global variable (that is, a variable on the window object) for method calls in the string literals form, while function pointer form calls, this is a complete error. The return value of the function is treated as a parameter of the setTimeout/setinterval function, which is not what we expect.
To solve this problem, we can use the anonymous function packaging method. In the following scenario, we do this:
Code:
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.
Other usage methods:
(SetTimeout (expression, delay time), in the execution, is in the loading delay after the specified time (MS), to execute an expression, remember, the number of times is once)
For example, the effect of displaying a random number is automatically changed using setTimeout:
<HTML>
<Head>
<SCRIPT>
Window. onload = sett;
Function sett ()
{
Document. Body. innerhtml = math. Random ();
SetTimeout ("sett ()", 500 );
}
</SCRIPT>
</Head>
<Body>
</Body>
</Html>
(Setinterval (expression, interaction time), it from the load, every specified time (MS) to execute an expression)
For example, use setinterval to automatically change the result of displaying a random number:
<HTML>
<Head>
<SCRIPT>
Function sett ()
{
Document. Body. innerhtml = math. Random ();
}
Setinterval ("sett ();", 500 );
</SCRIPT>
</SCRIPT>
</Head>
<Body>
</Body>
</Html>