SoFunction
Updated on 2025-03-01

Javascript delayed execution implementation method (setTimeout)

1. Delay switch tab
Requirements: 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 and cuts quickly to the end, n ajax requests will be generated. In fact, users just need to see the data of the last tab.
Copy the codeThe 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 is onmouseover bound to the tab. If the user constantly switches the tab back and forth, the ajax request will not be executed. It will only be executed after 500 milliseconds. 500 milliseconds are actually quite short and will basically not affect the user experience.

2. Delayed autocomplete
Requirements: In the text input box, listen to user input to achieve automatic completion function.
Disadvantage: Every time a user enters a character, an ajax request will be generated. If the user enters a long list of content in succession, the number of requests will be many. In fact, the last time is what the user needs.
The code is similar to the above example.

3. Delay scrolling
Requirements: The page advertisement needs to be followed wherever the user needs to scroll.
Disadvantage: The user scrolls at the bottom, triggering N times of the function to reposition the ad. In fact, it is enough to just trigger it once when the user stops.
The code is similar to 1.

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