Js timer setTimeout cannot call local Variables Solution _ javascript skills

Source: Internet
Author: User
In javascript, the timer setTimeout cannot call a local variable. You only need to change the first parameter of setTimeout to a function object instead of a string. The usage of the timer setTimeout in javascript is generally as follows, after beginrotate is called, a process of regularly executing rotateloop is started. The following code:

The Code is as follows:


Var angle = 0;

Function rotateloop (){
If (angle <360 ){
Angle ++;
// Use angle
//......
SetTimeout ("rotateloop ()", 100 );
}
}

Function beginrotate (){
// Do something
//......
SetTimeout ("rotateloop ()", 100 );
}


One problem with this Code is that a global variable angle is generated, which is obviously not a good programming habit. Therefore, we want to use nested functions to change the code to the following:

The Code is as follows:


Function beginrotate (){

Var angle = 0;

Function rotateloop (){
If (angle <360 ){
Angle ++;
// Use angle
//......
SetTimeout ("rotateloop ()", 100 );
}
}
// Do something
//......
SetTimeout ("rotateloop ()", 100 );
}


After this change, we found that the javascript error was reported and rotateloop could not be found. Obviously, the partial embedded function rotateloop was not found in setTimeout. Here we just need to change it to solve this problem. The Code is as follows:

The Code is as follows:


Function beginrotate (){

Var angle = 0;

Function rotateloop (){
If (angle <360 ){
Angle ++;
// Use angle
//......
SetTimeout (FIG, 100 );
}
}
// Do something
//......
SetTimeout (FIG, 100 );
}


You only need to change the first parameter of setTimeout to a function object instead of a string.
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.