How to pass parameters to setTimeout and setinterval

Source: Internet
Author: User

See the followingCode:

 
VaR STR = 'aaa'; var num = 2; function auto (Num) {alert (Num);} setTimeout ('Auto (Num) ', 4000 );

In this way, the write operation works normally, but if it is said that this is a parameter transfer, it is better to say that it is a directly used global variable. Therefore, this writing method is unnecessary. Generally, it is used to pass local variables as parameters.

Modify the Code:

 
// Var STR = 'aaa'; var num = 2; function test () {var STR = 'bbb'; setTimeout ('Auto (STR) ', 4000 );} function auto (a) {alert (a) ;}test ();

This write method reports an error. If you uncomment the global declaration on STR, AAA is output, that is, the function still calls global variables.

See the following code:

 
// Var STR = 'aaa'; var num = 2; function test () {var STR = 'bbb'; setTimeout ('Auto ("str ")', 4000);} function auto (a) {alert (a) ;}test ();

Note that the STR above will output "str". That is to say, after the timer calls the function, STR is directly treated as a parameter. The passed parameter is always a string. This is not the expected result.

To pass unexpected parameters except strings, you can use the closure. See the following code:

// Var STR = 'aaa'; var num = 2; function test () {var STR = 'bbb'; setTimeout (Auto (STR), 4000 );} function auto (STR) {return function () {alert (STR) ;}} test ();

The output is 'bbb '. If auto (STR) is enclosed in quotation marks, an error is returned.

Of course, this writing is also good:

 
VaR num = 2; function test () {var STR = 'bbb'; // setTimeout (Auto (STR), 4000); setTimeout (function () {alert (STR)}, 4000) ;}function auto (STR) {return function () {alert (STR) ;}} test ();

Note that when no closure is used to pass parameters, the function called by the timer must be enclosed by quotation marks. If no quotation marks are provided, an error is returned. The above situations are also suitable for setinterval ();

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.