JS Timer settimeout Unable to invoke local variable solution _javascript tips

Source: Internet
Author: User
The use of timer settimeout in JavaScript is generally as follows: After calling Beginrotate, you enter a process that executes the rotateloop in a timed, following code.
Copy Code code as follows:

var angle = 0;

function Rotateloop () {
if (angle < 360) {
angle++;
Use angle
//......
SetTimeout ("Rotateloop ()", 100);
}
}

function Beginrotate () {
Do something
//......
SetTimeout ("Rotateloop ()", 100);
}

The problem with this code is that it produces a global variable angle, which is obviously not a good programming habit, so we thought of using inline functions to change the code as follows:
Copy Code code 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, found JavaScript error, Rotateloop can not find, obviously settimeout did not find rotateloop this local inline function, here as long as a little change can solve the problem, the code is as follows:
Copy Code code as follows:

function Beginrotate () {

var angle = 0;

function Rotateloop () {
if (angle < 360) {
angle++;
Use angle
//......
settimeout (Rotateloop, 100);
}
}
Do something
//......
settimeout (Rotateloop, 100);
}

You just need to change the first argument of settimeout to a function object, not a string.

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.