Home  >  Article  >  Web Front-end  >  js timer setTimeout cannot call local variables solution_javascript skills

js timer setTimeout cannot call local variables solution_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:11:561285browse

The usage of timer setTimeout in JavaScript is generally as follows. After calling beginrotate, it enters a process of regularly executing rotateloop, as shown in the following code:

Copy 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);
}

There is a problem with this code, that is, it generates A global variable angle is obviously not a good programming habit, so we thought of using inline functions and changed the code to the following:
Copy code 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);
}

Changed like this After that, I found that JavaScript reported an error and rotateloop could not be found. Obviously setTimeout did not find the local embedded function rotateloop. This problem can be solved with a slight change. The code is as follows:
Copy code 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);
}

Just setTimeout Just change the first parameter to a function object instead of a string.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn