JavaScript function throttling (throttle) and function shake (debounce)

Source: Internet
Author: User

The function is executed at the time interval of throttle.

Debounce time interval T Nejo the event again, the timer is re-timed until the stop time is greater than or equal to T to execute the function.

1. Simple implementation of throttle function

functionThrottle (FN, threshhold, scope) {threshhold|| (threshhold = 250); varLast , timer; return function () {        varContext = Scope | | This; varnow = +NewDate (), args=arguments; if(Last && now-last + threshhold < 0) {             //Hold on to itcleartimeout (Defertimer); Timer= SetTimeout (function() { last=Now ;             Fn.apply (context, args);         }, threshhold); } Else{ Last=Now ;         Fn.apply (context, args); }     };}//Calling Methods$ (' body '). On (' MouseMove ', throttle (function(event) {Console.log (' Tick ');}, 1000));

2. Simple implementation of debounce function

functiondebounce (FN, delay) {varTimer =NULL; return function () {         varContext = This, args=arguments;         Cleartimeout (timer); Timer= SetTimeout (function() {fn.apply (context, args);     }, delay); };}//Calling Methods$ (' Input.username '). KeyPress (Debounce (function(event) {//Do the Ajax request}, 250));

Transferred from: http://www.cnblogs.com/fsjohnhuang/p/4147810.html

JavaScript function throttling (throttle) and function shake (debounce)

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.