Home >Web Front-end >JS Tutorial >A detailed explanation of how to use window.setTimeout()&window.setInterval() and how to pass parameters! _javascript skills

A detailed explanation of how to use window.setTimeout()&window.setInterval() and how to pass parameters! _javascript skills

WBOY
WBOYOriginal
2016-05-16 19:07:441108browse

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:

Copy code The code is as follows:

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);
Copy code The code is as follows:

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:
Copy code The code is as follows:

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn