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 the 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);
}
One problem with this code is that it generates a global variable angle, which is obviously not a good programming practice, so we thought of using inline functions and changed the code to the following:
Copy the 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 making this change, I found that JavaScript reported an error and rotateloop could not be found. Obviously setTimeout did not find the local embedded function of rotateloop. This problem can be solved with a slight change. The code is as follows:
Copy the 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);
}
Just change the first parameter of setTimeout to a function object instead of a string.