Implementation of Javascript delayed execution (setTimeout) _ javascript tips-js tutorial

Source: Internet
Author: User
The setTimeout function is used for delayed execution. Good at using this function can reduce a lot of ajax requests and dom operations. 1. Delay switching tab
Requirement: There are several tabs on the page. When you switch to a tab, the data in a specific area is pulled and updated.
Disadvantage: You can quickly switch from the first tab to the end, and then generate n ajax requests. In fact, the user only needs to see the data of the last tab.

The Code is as follows:


Var changeTab = function (){
Var timeId = 0;
Return function (tabId ){
If (timeId ){
ClearTimeout (timeId );
TimeId = 0;
}
SetTimeout (function (){
// Ajax do something
},500 );
};
}();


A simple example is the onmouseover bound to the tab. If the user switches the tab repeatedly, the ajax request will not be executed. The request will only be executed after 500 milliseconds of pause, 500 milliseconds, in fact, it is quite short and basically does not affect the user experience.

2. Automatic delay completion
Requirement: In the text input box, listen to user input for Automatic completion.
Disadvantage: each time a user inputs a character, an ajax request is generated. If the user continuously inputs a long string of content, there are many requests. In fact, the last one is what the user needs.
The code is similar to the above example.

3. Delayed Rolling
Requirement: The page advertisement, where the user needs to scroll, should be followed.
Disadvantage: Users scroll to the bottom and trigger N times to reposition the advertisement. In fact, it is enough to trigger it once only when the user stops.
The code is similar to 1.

In fact, there are many such examples. Some things do not need to be executed immediately. They can be executed only after a little delay. The time is short and does not affect the user experience, and can reduce a lot of unnecessary consumption.

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.