A simple demand, click a button, then request resources to the server, no processing, many times there will be a number of requests waiting. The rough solution is to disable the button once and click. May I ask if there is a better way, such as more than one time after the automatic down off the previous request? Add: Not a request, more like Gmail's full-site Ajax, just used Firebug to look at Gmail, found a duplicate request, the previous request status changed to "aborted", and do not reverse any data back. How do we do that, please? After all, it is generally understood that client Ajax cannot be terminated after it is sent.
A. Exclusive submissions
Only one commit operation is allowed at a time, and the next commit cannot be made until this commit is complete.
module. Submit = function () {if (this. Promise_. State () === ' pending ' ) {return } return this. Promise_ = $. Post ( '/api/save ' ) }
B. Greedy type submission
Unlimited commits, but whichever is the last one, i.e. the feedback from the last operation needs to be given as soon as possible, and the result of the previous operation is not important.
module.submit = function() { if (this.promise_.state() === ‘pending‘) { this.promise_.abort() } // todo}
For example, in some applications, there are two-state buttons that do something like "like" or "dislike". If not immediately after pressing the feedback, the user's focus on the button may pause for a long time, if you press the status of the instant Switch button, and then the program with abort to achieve positive submissions, which can improve the user experience, but also reduce the server pressure, happy.
C. Moderation Submission
No matter how frequently the submission occurs, the interval between any two valid commits must be greater than or equal to a certain time interval, i.e. submitted at a certain frequency.
module.submit = throttle(150, function() { // todo})
If the customer sends 10 requests every 100 milliseconds, the module will only receive 6 of them (each on the timeline is 150 milliseconds away) for processing.
This is also an optional way to resolve query conflicts, for example, in the light of the draft example, careful observation can be found:
The Blur event of the editor triggers the save immediately;
The Click event of the Save button will also trigger the save immediately;
But there is a situation where the two events occur consecutively in a matter of milliseconds-when the focus is inside the editor and the Save button is clicked directly-it is possible to use throttle to handle it.
There are also some event handlers that use throttle frequently, such as: resize, scroll, MouseMove.
D. Lazy Type submission
The interval between any two commits must be greater than a specified time to contribute to a valid submission, i.e. no rest or work.
module.submit = debounce(150, function() { // todo})
Or to know the draft example, when you press CTRL + S in the editor, you can save the draft manually; If you double-click, the program will not understand why you have to double-click, it will continue until you give up the double-click.
============
More examples of memory
The way C and the way D are sometimes more generic, such as these conditions:
- In the game you pick up a powerful high-speed weapon, in order to prevent your bullets on the screen into a straight line, you can throttle to control the frequency;
- In the bomb screen type game, in order to prevent you to hold the shooting key to play without the brain game, you can use debounce to control the frequency;
- In the compilation task, the daemon monitors all files in a folder (such as any file changes can trigger recompilation, one execution takes 2 seconds), but an operation can instantly cause a large number of file changes (such as Git checkout), then a simple debounce You can make the compilation task execute only once.
and mode C can even be used in combination with the way B, such as auto-complete components (Google home search is):
- When the user quickly enters the text (especially the typing expert), can throttle the KeyPress event handler function, to specify the time interval to extract the text field the value, then immediately makes the new query;
- When the new query needs to be sent, but the previous query has not returned the results, you can abort the unfinished query and send the new query immediately;
-----Update 2013-01-08-----
E. Memory Type
var scrape = memoize(function(url) { return $.post(‘/scraper‘, { ‘url‘: url })})
For the same argument, its return always results in an identity-the same object is returned each time.
The application example has an editor, such as the paste content when the link information is crawled, memoize to ensure that the same link will not be crawled two times.
-----Update 2013-03-27-----
F. Cumulative type
This function was obtained the day before when the auto-complete event was processed, and the discovery could also be used to process continuous events, which could combine successive commits into a single commit, such as:
VarRequest=Makepile(5,function(){$.Post(‘/‘,{List:Json.Stringify([].Slice.Pager(Arguments))})}) //sent five times request ({a :1}), request ({ a:2}), request ({a:3}), Request ({a:4}), request ({a:5 }) /* post =>list:[{"a": 1},{"a": 2},{"a": 3},{"a": 4},{"a": 5}]< Span class= "cm" > */
Example implementation:
VarMakepile=function(Count,OnFilter,Onvalue){VarValues=[],Id=function(Value){ReturnValue}Returnfunction(Value){values. Push ((onvalue | | id). apply (thisarguments if (values. Length === count {onfilter< Span class= "P". apply (thisvalues ) values = [] }< Span class= "P" >
-----Update 2013-04-16-----
Another accumulation is by time, not the number of times, such as the application of behavioral statistics, may be collected in an instant dozens of hundreds of similar behavior, you can use the above pile structure plus debounce to prevent a large number of repeated requests (but do not lose any statistics):
VarTrackfactory=function(Delay,Action){VarParams=[],Slice=[].SliceVarTouch=Debounce(Delay,function(){If(Params.Length){Action(Params)Params= [] } }) return Function () {params. Push (slice. Call (argumentstouch () }}var track = Trackfactory (550function Span class= "NX" >params) {//send tracking Request )
G. Sample Type
This is a recent refactoring thought, a different from the above to redo the operation can be applied to the automatic loading (timeline) behavior control:
autoload.listen(feeds, ‘next‘, sample(3, function() { this.enable()}))
If sample is a cured selection function (n selected 1), it will actually work like this:
O-O-X-O-O-X
But the "Auto-load" app may want to be (two times automatic, one time manually):
X-X-O-X-X-O
For this scenario, you can define a selection function as a configuration to implement the control:
options { sample: (n) => n % 3 !== 0 }
That is, each time the next load is completed, the next load is automatically loaded two times every three times.
How can I prevent the repeated sending of Ajax requests?