Valerii Vasin (valerii) wrote in changelog,
Valerii Vasin
valerii
changelog

[livejournal] r23323: LJSUP-14309: Implement LJ.debounce() fun...

Committer: vvasin
LJSUP-14309: Implement LJ.debounce() function.
U   trunk/htdocs/js/basic.js
Modified: trunk/htdocs/js/basic.js
===================================================================
--- trunk/htdocs/js/basic.js	2012-11-19 13:34:44 UTC (rev 23322)
+++ trunk/htdocs/js/basic.js	2012-11-19 13:42:50 UTC (rev 23323)
@@ -264,6 +264,48 @@
 };
 
 /**
+ * Returns a function, that, as long as it continues to be invoked, will not
+ * be triggered. The function will be called after it stops being called for
+ * N milliseconds. If `immediate` is passed, trigger the function on the
+ * leading edge, instead of the trailing.
+ *
+ * Notice: signature and documentation has been taken from `underscore` project
+ *
+ * @param  {Function} func    Function to be called
+ * @param  {Number} wait      Amount of milliseconds to wait before invocation
+ * @param  {Boolean} [immediate] Invocation edge
+ * @return {Function}           Debounced function `func`
+ */
+LJ.debounce = function (func, wait, immediate) {
+	'use strict';
+
+	var timeout, result;
+
+	return function () {
+		var context = this,
+			args = arguments,
+			later,
+			callNow = immediate && !timeout;
+
+		later = function() {
+			timeout = null;
+			if ( !immediate ) {
+				result = func.apply(context, args);
+			}
+		};
+
+		clearTimeout(timeout);
+		timeout = setTimeout(later, wait);
+
+		if (callNow) {
+			result = func.apply(context, args);
+		}
+
+		return result;
+	};
+},
+
+/**
  * Create function that will call target function at most once
  * per every delay. Arguments are queued and when delay ends
  * function is called with last supplied arguments set. Optionally

Tags: invis89, js, livejournal, vvasin
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments