In JS, whether it is setTimeout or setInterval, you cannot take parameters when using the function name as the calling handle. In many cases, you must take parameters.
This requires finding a way to solve it.
1. Use string form: - (Defect) Parameters cannot be changed periodically
setInterval("foo(id)",1000);
2. Anonymous function packaging (recommended)
window.setInterval(function()
{
foo (id);
}, 1000);
In this way, the function foo(id) can be executed periodically and the variable id is passed in;
3. Definition of return without parameters Function of function
function foo(id)
{
alert(id);
}
function _foo(id)
{
return function()
{
foo(id);
}
}
window.setInterval(_foo(id),1000);
A function _foo is defined here to receive a parameter and return a function without parameters. In this The parameters of the external function are used inside the function, so there is no need to use parameters when calling it.
In the window.setInterval function, use _foo(id) to return a function handle without parameters, thus realizing the parameter passing function.
4. Modify 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 the above methods are also suitable for setTimeout.
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