Use a function proxy that limits the frequency of function execution

Source: Internet
Author: User

Use a function proxy that limits the frequency of function execution
Use a proxy to limit the frequency of function calls

Assume that an Ajax asynchronous query function is required on a classic CURD page.
Put a query button and click query. The system sends a data request to the remote server and returns the query result one second later.

Soon!
But what happens if the user clicks three queries in one second?

To solve this problem, we may disable the query button after the user clicks the query button, or lock the query during processing, and release the lock after returning the result.
Well, it is enough for daily use.

Here, only one problem is solved: click the button. How can we solve the problem of high frequency of triggering of input box input, selection box changes, mouse movement, and scroll wheel?
For comprehensive consideration, we don't need to repeat ourselves. A solution came into being: using function proxies that limit the frequency of function execution.

The API of this function looks a little like setTimeout and Promise, but it is slightly different in form.
I plan to recommend it to ES6. Unfortunately, the String Padding API sent by the front-end event is blocked several times by the firewall.
Alas! I can only talk about it in my blog.

Function

/*** Create a proxy function with Frame Rate Control for the function * contains details at the end * Note: this Function is applicable when the call interval is greater than 1 ms * @ static * @ method getFPSLimitedFunction * @ param {Function} accept-specified Function * @ param {Number} [fps = 0]-per second the maximum number of executions. (Set interval to the number of milliseconds at the interval. This value is equivalent to 1000/interval.) * @ param {Function} [reject = null]-callback When execution is denied. * @ Returns {Function} agent-proxy function * @ throws {TypeError} called_non_callable-this error is thrown if accept is not a function */Function getFPSLimitedFunction (accept, reject, fps) {if (typeof accept! = "Function") {throw new TypeError (accept + "is not a function");} if (typeof reject! = "Function") {reject = null;} fps >>>= 0; var delay = Math. max (/fps), locked = false, timer = 0, rejectedQueue = [], lastAcceptedTime = 0, lastRejectedTime = 0; var lock = function () {locked = true ;}; var unlock = function () {locked = false; clearTimeout (timer); timer = setTimeout (checkrejectedcils, delay);}; var checkrejectedcils = function () {if (lastAcceptedTime
 
  
0) {if (typeof reject = "function") {for (I = 0; I
  
   

Use Cases

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Demo1 limits the frequency of function calls for event listening //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ // Add a mouse movement event listener for the document. The listener can execute a maximum of 25 times per second. var document_mousemoveHandler = getFPSLimitedFunction (function (event) {// TODO handles mouse movement}, null, 25 ); document. addEventListener ("mousemove", document_mousemoveHandler); // adds a click event listener for the query button. The listener can execute a maximum of one var button_clickHandler = getFPSLimitedFunction (event) per second) {// TODO query data}, null, 1); document. querySelector ("# searchButton "). addEventListener ("click", button_clickHandler );//~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ // Demo2: Add a mouse movement event listener to the document, the listener can be executed for up to 60 times per second //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Demo2function doSomethingWithIntervalAndTimes (something, interval, times) {var count = 0; var timer = setInterval (function () {count ++; if (count> = times) {clearTimeout (timer) ;}something (count, times) ;}, interval); return timer ;}// a maximum of one var showMessage = getFPSLimitedFunction (function accept (s) can be accepted once in 1 second) {// accept the business console. log ("accepted:" + s) ;}, function reject (s) {// process rejected console. warn ("rejected:" + s) ;}, 1); // once every MS (10 FPS), theoretically accepted once per second, doSomethingWithIntervalAndTimes (function (currentCount, repeatCount) {showMessage (currentCount) ;}, 100,100 );


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.