[JavaScript] Using setTimeout to reduce unnecessary events

Source: Internet
Author: User

In the browser, some events are triggered very frequently, almost within milliseconds. The most typical event is document. onmousemove. Such frequent events often do more harm than good. Today we can see a good solution. Here we can slightly improve it into a general method. Although it cannot completely solve the problem, it can be effectively mitigated and easy to use.CodeAs follows:

 
// The FN var onfooendfunc = function (FN) {var delay = 50 that supports parameter passing. // you can adjust the latency based on the actual situation. var executiontimer; return function () {If (!! Executiontimer) {cleartimeout (executiontimer) ;}// your function executiontimer = setTimeout (function () {// alert ('20140901'); FN ();}, delay );};};

The document. onmousemove is used as an example to check the running effect. Before processing with latency, move the mouse and you will find that the event is triggered very frequently. After processing with latency, move the mouse and the event will be less frequently.




<textarea id="TextArea1" name="S1" style="height: 40px; width: 200px; color: #ff0000; clip: rect(auto, auto, auto, auto);"></textarea>

The above is just a document. onmousemove is used as an example. There are many other DOM events with the same problem, such as onscroll, onmousemove, and onresize. Similarly, you can use this method to solve the problem. For details, refer to the example here, methods are essentially the same.

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.