Problems and Solutions for using setTimeout and setInterval in requireJS

Source: Internet
Author: User

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.


Related Article

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.