This article describes the concept and usage of JavaScript function throttling. Share it for your reference, as follows:
Recently, when I was making web pages, I had a requirement, which was to change some page element sizes when the browser window changed, so I naturally thought of the resize event of the window, so I wrote this
<!DOCTYPE html><html><head> <title>Throttle</title></head><body> <script type="text/javascript"> n=0; function resizehandler(){ console.log(new Date().getTime()); console.log(++n); } window.onresize=resizehandler; </script></body></html>The function is implemented, but when I drag and drop the way I change the browser window size, I looked at the console
That's right, a simple drag and drop made my resizeHandler() method execute 52 times, which is not the effect I want at all. In fact, the code of my resizeHandler() method is very complicated, and I even use ajax to send requests to the server. If I simply change the window size at a time, I have to call 52 times. This is a big deal.
Function throttling
In fact, my original intention is to make some adjustments to the page after the window is resize. The resize event of the window is not triggered after the resize ends. I don’t know the specific frequency, but it is constantly calling until the window size does not change. In fact, similar mechanisms and mousemove are triggered repeatedly in a short period of time.
There are functions throttling that specifically deal with this problem in JavaScript Advanced Programming
function throttle(method,context){ clearTimeout(method.tId); method.tId=setTimeout(function(){ method.call(context); },500);}The principle is very simple. Use a timer to delay the execution of the function by 500 milliseconds. If a function is called again within 500 milliseconds, the last call will be deleted. This time the call will be executed after 500 milliseconds, and this will be repeated. In this way, my code just now can be changed to
<script type="text/javascript">n=0;function resizehandler(){ console.log(new Date().getTime()); console.log(++n);}function throttle(method,context){ clearTimeout(method.tId); method.tId=setTimeout(function(){ method.call(context); },500);}window.onresize=function(){ throttle(resizehandler,window);};</script>Try dragging and dragging, it was only executed once
Another way to do it
There is also a function throttling solution online, which does this
function throttle(method,delay){ var timer=null; return function(){ var context=this, args=arguments; clearTimeout(timer); timer=setTimeout(function(){ method.apply(context,args); },delay); }}Try calling it, the same effect
<script type="text/javascript">n=0;function resizehandler(){ console.log(new Date().getTime()); console.log(++n);}function throttle(method,delay){ var timer=null; return function(){ var context=this,args=arguments; clearTimeout(timer); timer=setTimeout(function(){ method.apply(context,args); },delay); }}window.onresize=throttle(resizehandler,500);//Because the function handle is returned, there is no need to wrap the function</script>Compare
Both methods use setTimeout. The difference is that the function added by the second method delays the execution time. This is easy to have this function in the first solution, adding a parameter.
But the first option sets tId as a variable of the function to save, while the second option creates a closure to store. I personally think the gap is not big, and I like the first one, which is simple and efficient.
New demand
One day I made something similar, just like the automatic prompt for input on Baidu homepage. I bound the keyup event on the text. It automatically prompts every time the keyboard pops up, but I don’t want to prompt so often. So I used the above method, but it was tragic. I only stopped input and waited for 500 milliseconds to prompt, and there was no prompt at all during the input process. I looked at the code and found that it wasn't true. As long as the user would type blindly, press the keyboard within 500 milliseconds, the prompt function would be continuously delayed. This would only prompt when I stopped, which would be meaningless.
Can it be executed once at a fixed time based on function throttling?
Small changes
I searched online and we can make some changes based on the second writing method (the first one is a bit bad for expanding multiple variables for functions), and add a parameter as the fixed interval must be executed.
function throttle(method,delay,duration){ var timer=null, begin=new Date(); return function(){ var context=this, args=arguments, current=new Date();; clearTimeout(timer); if(current-begin>=duration){ method.apply(context,args); begin=current; }else{ timer=setTimeout(function(){ method.apply(context,args); },delay); } }}In this way, we will determine how long the interval is. If the setting time is exceeded, we will execute it immediately. Use the example just now to try the effect
window.onresize=throttle(resizehandler,100,200);
It's true that there is no frequent execution or final execution
For more information about JavaScript related content, please check out the topics of this site: "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm skills", "Summary of JavaScript animation effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm skills", "Summary of JavaScript traversal algorithms and techniques", and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.