Solve the problem of using window. setTimeout () & window. setInterval () and passing parameters! _ Javascript skills

Source: Internet
Author: User
Solve the problem of using window. setTimeout () & amp; window. setInterval () and passing parameters! When using JScript, we sometimes need to execute a method at intervals, for example, to generate webpage UI animation effects. This is often the setInterval or setTimeout method, but since these two methods are the Timer threads simulated by the Script Host, our method through which we call cannot pass parameters for them.

Our common application scenarios are:

The Code is as follows:


Window. setTimeout ("delayRun ()", n );
Window. setInterval ("intervalRun ()", n );
Window. setTimeout (delayRun, n );
Window. setInterval (intervalRun, n );


Apparently, the parameter is forcibly called: window. setTimeout ("delayRun (param)", n );

The Code is as follows:


Window. setInterval ("intervalRun (param)", n );
Window. setTimeout (delayRun (param), n );
Window. setInterval (intervalRun (param), n );


All of them are incorrect. Because the method call in the string literals form must be a global variable (that is, the variable in the window object), and the call in the function pointer form is totally wrong, this regards the return value of the function as the parameter of the setTimeout/setInterval function, which is not what we want at all.

To solve this problem, we can use the anonymous function packaging method. In the following scenario, we do this:

The Code is as follows:


Function foo ()
{
Var param = 100;
Window. setInterval (function ()
{
IntervalRun (param );
},888 );
}

Function interalRun (times)
{
// Todo: depend on times parameter
}

In this way, you can no longer rely on global variables to pass parameters to the delayRun/intervalRun functions. After all, when there are more global variables on the page, it will bring huge puzzle to the development, debugging, and management of scripts.
Related Article

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.