JS transfer function: JS setinterval, settimeout can not pass the function with parameters to solve the solution

Source: Internet
Author: User
Tags functions return setinterval window
In JS, whether settimeout or setinterval, use the function name as the call handle can not take parameters, and in many cases must take parameters,
This needs to be solved in a way.
First, in the form of a string:--(defect) parameters can not be periodically changed
SetInterval ("foo (ID)", 1000);
Second, anonymous function packaging (recommended)
Window.setinterval (function ()
{
Foo (ID);
}, 1000);
This allows you to periodically execute the Foo (ID) function and pass the variable ID in;
Iii. defining functions that return parameterless functions
function foo (ID)
{
alert (ID);
}
function _foo (ID)
{
return function ()
{
Foo (ID);
}
}
Window.setinterval (_foo (ID), 1000);
This defines a function _foo, which receives a parameter and returns a function with no parameters, which uses the arguments of the external function inside the function to invoke it without using parameters.
In window. In the SetInterval function, the _foo (ID) is used to return a function handle with no parameters, thus enabling the function of parameter passing.
Iv. Modification of 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 of the above methods are also suitable for settimeout.
This article links http://www.cxybl.com/html/wyzz/JavaScript_Ajax/20130712/39060.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.