In JS, setInterval and setTimeout cannot pass the solution of functions with parameters _ javascript skills

Source: Internet
Author: User
In JS, whether it is setTimeout or setInterval, parameters cannot be included when using the function name as the call handle. In many cases, parameters must be included, next we will introduce the specific solution. In JS, whether it is setTimeout or setInterval, parameters cannot be included when using the function name as the call handle. In many cases, parameters must be included,
This requires a solution.
1. Use a string: The -- (defect) parameter cannot be periodically changed
SetInterval ("foo (id)", 1000 );
Ii. Anonymous function packaging (recommended)

The Code is as follows:


Window. setInterval (function ()
{
Foo (id );
},1000 );


In this way, the foo (id) function can be periodically executed and the variable id can be passed in;
3. Define a function that returns a function without Parameters

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, which is used to receive a parameter and return a function without a parameter. An external function parameter is used inside the function to call it, no parameters are required.
In the window. setInterval function, _ foo (id) is used to return a function handle without parameters, thus implementing the function of passing parameters.
4. Modify setInterval

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.

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.