Problems and Solutions for using setTimeout and setInterval in requireJS
The timing-related APIs in javascript include setTimeout () and setInterval (). These two functions have different functions, but they are used in the same way.
In javascript, the following statement defines a closed space, and the variables and functions defined in it are private and can only be accessed in this module.
(Function () {var msg = "msg" ;}) (); // Error alert (msg );
Previously, I used setTimeout ("say ('aty');", 1000) to write javascript. In this way, because say is a global function, it can run correctly. A recent project uses the requireJS framework, which requires us to write javascript in a modular way. In the previous method, using setTimeout won't work.
(Function () {function say (msg) {alert (msg) ;}// 1st Methods // setTimeout ("say ('aty');", 1000 ); // 2nd Methods // setTimeout (say ("aty"), 1000); // 3rd Methods setInterval (function () {say ("aty ");}, 1000 );})();
The first method reports an error because the say function is only visible within the module and the setTimeout function is invisible;
Method 2: the code will be executed immediately, and the latency does not reach the setTimeout;
Method 3: using this anonymous function call can meet our needs, that is, to solve the problem of latency and the problem of variable visible domain.