Home > Web Front-end > JS Tutorial > Solution to the problem that setInterval and setTimeout cannot pass functions with parameters in JS_javascript skills

Solution to the problem that setInterval and setTimeout cannot pass functions with parameters in JS_javascript skills

WBOY
Release: 2016-05-16 17:35:03
Original
1147 people have browsed it

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)

Copy code The code is as follows:

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

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

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.
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template