JavaScript latency Execution Implementation method (SetTimeout) _javascript tips

Source: Internet
Author: User
1. Delay Toggle Tab
Requirements: There are several tabs on the page, and when you switch tab, the data in a particular area is pulled up and updated.
Disadvantage: The user from the first tab switch has been fast cut to the end, will produce n Ajax requests. In fact, users just need to see the last tab data.
Copy Code code as follows:

var changetab = function () {
var Timeid = 0;
return function (tabid) {
if (Timeid) {
Cleartimeout (Timeid);
Timeid=0;
}
settimeout (function () {
Ajax do Something
},500);
};
}();

A relatively simple example, binding on the tab onmouseover, if the user constantly switching back and forth Tab,ajax request will not be executed, only after a pause of 500 milliseconds, will execute, 500 milliseconds, in fact, quite short, basically will not affect the user experience.

2. Delay Automatic Completion
Requirements: In the text input box, listening for user input, to achieve the function of automatic completion.
Disadvantages: Each user input a character, will produce an AJAX request, if the user entered a long string of content, the number of requests are many, in fact, the last time, is the user needs.
The code is similar to the example above.

3. Deferred scrolling
Requirements: page ads, users need to scroll to where to follow.
Disadvantage: User scrolling at the bottom, triggering the N times to let the ads reposition function. In fact, only when the user stops, only the trigger once is enough.
The code is similar to 1.

In fact, there are many such examples, some things, do not need to execute immediately, can delay a little time to execute, the time is very short, do not affect the user experience, but also reduce a lot of unnecessary consumption.
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.