When using JScript, we sometimes need to execute a method at intervals, such as to generate web page UI animation effects or something. This is the method we often use setInterval or setTimeout, but since these two methods are Timer threads simulated by the script host, parameters cannot be passed to them when calling our methods.
Our common usage scenarios are:
window.setTimeout("delayRun()", n);
window.setInterval("intervalRun()", n);
window.setTimeout(delayRun, n);
window. setInterval(intervalRun, n);
Obviously force the call to substitute parameters: window.setTimeout("delayRun(param)", n);
window.setInterval("intervalRun(param)", n);
window.setTimeout(delayRun(param) , n);
window.setInterval(intervalRun(param), n);
are all wrong, because when calling methods in the form of string literals, param must be a global variable (i.e. window object variables); and the call in the function pointer form is completely wrong. This is treating the return value of the function as the parameter of the setTimeout/setInterval function, which is not what we expect at all.
The solution to this problem can be to use anonymous function packaging. In the following scenario we do this:
function foo()
{
var param = 100;
window.setInterval(function()
{
intervalRun( param);
}, 888);
}
function internalRun(times)
{
// todo: depend on times parameter
}
In this way, you can no longer rely on global variables to pass parameters to the delayRun/intervalRun function. After all, when there are too many global variables in the page, it will bring great puzzles to the development, debugging and management of scripts.