Js timer setTimeout cannot call local variables solution
- 2020-03-30 00:02:03
- OfStack
The usage of timer setTimeout in javascript is generally as follows. After calling beginrotate, it enters a process of timing execution of rotateloop, as follows:
This code has a problem, is produced a global variable Angle, which is obviously not a good programming habit, so we thought of using the way of embedded function, the code as follows:
After this is changed, found javascript error, rotateloop can not find, obviously setTimeout did not find the rotateloop this local nested function, here as long as a little change can solve the problem, the code is as follows:
All you need to do is change the first argument of setTimeout to a function object, not a string.
var angle = 0;
function rotateloop() {
if (angle < 360) {
angle++;
//use angle
//......
setTimeout("rotateloop()", 100);
}
}
function beginrotate() {
//do something
//......
setTimeout("rotateloop()", 100);
}
This code has a problem, is produced a global variable Angle, which is obviously not a good programming habit, so we thought of using the way of embedded function, the 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 is changed, found javascript error, rotateloop can not find, obviously setTimeout did not find the rotateloop this local nested function, here as long as a little change can solve the problem, 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);
}
All you need to do is change the first argument of setTimeout to a function object, not a string.