JavaScript function limits calling code _javascript tips

Source: Internet
Author: User
Function:

Copy Code code as follows:

Function Throttle (FN,MS) {
var last = (new Date ()). GetTime ();
Return (function () {
var now = (new Date ()). GetTime ();
if (Now-last > ms) {
last = Now;
Fn.apply (this, arguments);
}
});
}

PARAMETER fn: Incoming function/method
Parameter MS: the interval (in milliseconds) for each function call, such as input 2000, the function does not repeat in 2 seconds.

An example of initialization

Copy Code code as follows:

document.getElementById (' Pop '). onclick = throttle (function () {
alert (this.id);
},2000)


The scope is set to the caller itself
Fn.apply (this, arguments);

Examples
<! DOCTYPE html> <ptml xmlns= "http://www.w3.org/1999/xhtml" > <HEAD> <TITLE> New Flowers </TITLE&G T </HEAD> <style type= ' text/css ' > #pop {width:100px; height:100px; Background: #ccc; } </style> <BODY> <div id= "Pop" > virtual bit has been waiting </div> </BODY> </HTML> <script type= ' text /javascript ' > Function throttle (fn,ms) {var last = (new Date ()). GetTime (); Return (function () {var now = (new Date ()). GetTime (); if (Now-last > ms) {last = now; Fn.apply (this, arguments); } }); } document.getElementById (' Pop '). onclick = throttle (function () {alert (this.id); },2000) </script>
[ctrl+a All selected note: If you need to introduce external JS need to refresh to perform]
Related Article

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.