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.