Home > Web Front-end > JS Tutorial > Javascript delayed execution implementation method (setTimeout)_javascript skills

Javascript delayed execution implementation method (setTimeout)_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 18:12:47
Original
1016 people have browsed it
1. Delayed tab switching
Requirement: There are several tabs on the page. When switching tabs, the data in a specific area will be pulled and updated.
Disadvantage: If the user switches from the first tab to the end quickly, n ajax requests will be generated. In fact, the user only needs to see the data of the last tab.
Copy code 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 relatively simple example, bind onmouseover on tab, if The user keeps switching tabs back and forth, and the ajax request will not be executed. It will only be executed after a pause of 500 milliseconds. 500 milliseconds is actually quite short and will basically not affect the user experience.

2. Delayed auto-complete
Requirement: In the text input box, monitor user input to implement the auto-complete function.
Disadvantages: Every time the user inputs a character, an ajax request will be generated. If the user continuously inputs a long string of content, the number of requests will be many. In fact, the last one is what the user needs.
The code is similar to the example above.

3. Delayed scrolling
Requirement: The advertisement on the page should follow wherever the user scrolls.
Disadvantage: The user scrolls to the bottom, triggering the function to reposition the advertisement N times. In fact, it only needs to be triggered once 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 delayed for a while. The time is very short, does not affect the user experience, and can reduce a lot of unnecessary consumption.
Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template