Throttle event calls in jQuery - javascript

I have a keyup event bound to a function that takes about a quarter of a second to complete.
$("#search").keyup(function() {
//code that takes a little bit to complete
});
When a user types an entire word, or otherwise presses keys rapidly, the function will be called several times in succession and it will take a while for them all to complete.
Is there a way to throttle the event calls so that if there are several in rapid succession, it only triggers the one that was most recently called?

Take a look at jQuery Debounce.
$('#search').keyup($.debounce(function() {
// Will only execute 300ms after the last keypress.
}, 300));

Here is a potential solution that doesn't need a plugin. Use a boolean to decide whether to do the keyup callback, or skip over it.
var doingKeyup = false;
$('input').keyup(function(){
if(!doingKeyup){
doingKeyup=true;
// slow process happens here
doingKeyup=false;
}
});

You could also use the excellent Underscore/_ library.
Comments in Josh's answer, currently the most popular, debate whether you should really throttle the calls, or if a debouncer is what you want. The difference is a bit subtle, but Underscore has both: _.debounce(function, wait, [immediate]) and _.throttle(function, wait, [options]).
If you're not already using Underscore, check it out. It can make your JavaScript much cleaner, and is lightweight enough to give most library haters pause.

Here's a clean way of doing it with JQuery.
/* delayed onchange while typing jquery for text boxes widget
usage:
$("#SearchCriteria").delayedChange(function () {
DoMyAjaxSearch();
});
*/
(function ($) {
$.fn.delayedChange = function (options) {
var timer;
var o;
if (jQuery.isFunction(options)) {
o = { onChange: options };
}
else
o = options;
o = $.extend({}, $.fn.delayedChange.defaultOptions, o);
return this.each(function () {
var element = $(this);
element.keyup(function () {
clearTimeout(timer);
timer = setTimeout(function () {
var newVal = element.val();
newVal = $.trim(newVal);
if (element.delayedChange.oldVal != newVal) {
element.delayedChange.oldVal = newVal;
o.onChange.call(this);
}
}, o.delay);
});
});
};
$.fn.delayedChange.defaultOptions = {
delay: 1000,
onChange: function () { }
}
$.fn.delayedChange.oldVal = "";
})(jQuery);

Two small generic implementations of throttling approaches. (I prefer to do it through these simple functions rather than adding another jquery plugin)
Waits some time after last call
This one is useful when we don't want to call for example search function when user keeps typing the query
function throttle(time, func) {
if (!time || typeof time !== "number" || time < 0) {
return func;
}
var throttleTimer = 0;
return function() {
var args = arguments;
clearTimeout(throttleTimer);
throttleTimer = setTimeout(function() {
func.apply(null, args);
}, time);
}
}
Calls given function not more often than given amount of time
The following one is useful for flushing logs
function throttleInterval(time, func) {
if (!time || typeof time !== "number" || time < 0) {
return func;
}
var throttleTimer = null;
var lastState = null;
var eventCounter = 0;
var args = [];
return function() {
args = arguments;
eventCounter++;
if (!throttleTimer) {
throttleTimer = setInterval(function() {
if (eventCounter == lastState) {
clearInterval(throttleTimer);
throttleTimer = null;
return;
}
lastState = eventCounter;
func.apply(null, args);
}, time);
}
}
}
Usage is very simple:
The following one is waiting 2s after the last keystroke in the inputBox and then calls function which should be throttled.
$("#inputBox").on("input", throttle(2000, function(evt) {
myFunctionToThrottle(evt);
}));
Here is an example where you can test both: click (CodePen)

I came across this question reviewing changes to zurb-foundation. They've added their own method for debounce and throttling. It looks like it might be the same as the jquery-debounce #josh3736 mentioned in his answer.
From their website:
// Debounced button click handler
$('.button').on('click', Foundation.utils.debounce(function(e){
// Handle Click
}, 300, true));
// Throttled resize function
$(document).on('resize', Foundation.utils.throttle(function(e){
// Do responsive stuff
}, 300));

Something like this seems simplest (no external libraries) for a quick solution (note coffeescript):
running = false
$(document).on 'keyup', '.some-class', (e) ->
return if running
running = true
$.ajax
type: 'POST',
url: $(this).data('url'),
data: $(this).parents('form').serialize(),
dataType: 'script',
success: (data) ->
running = false

Related

How to check if an api call has completed

I have a script in my code
<script src="https://geodata.solutions/includes/statecity.js"></script>
which is making an ajax call. This script is used to fetch states and cities and loads the value in select. How do I check whether that particular call is complete as it is in this external script and I want to set value of select using javascript/jquery
I am currently using setTimeout for setting select value and delaying it randomly for 6 seconds however it's not the right approach. Also, I have tried putting the code to set value in $(document).ready() but the api call returns the values later
setTimeout(function(){
jQuery("#stateId").val('<?php echo $rowaddress['state']; ?>').change();
setTimeout(function(){
jQuery("#cityId").val('<?php echo $rowaddress['city']; ?>').change();
}, 3000);
}, 6000);
spy on jQuery.ajax:
jQuery.ajax = new Proxy(jQuery.ajax, {
apply: function(target, thisArg, argumentsList) {
const req = target.apply(thisArg, argumentsList);
const rootUrl = '//geodata.solutions/api/api.php';
if (argumentsList[0].url.indexOf(rootUrl) !== -1) {
req.done(() => console.log(`request to ${argumentsList[0].url} completed`))
}
return req;
}
});
Having a look through the code for statecity.js, I've just seen that:
jQuery(".states").prop("disabled",false);
is executed upon completion of initial loading. This is on line 150 of the source code.
You could monitor the disabled attribute of the .states selector to be informed when the activity is completed using the handy JQuery extension watch.
To detect the completion of the event, just watch the disabled property of the .states item:
$('.states').watch('disabled', function() {
console.log('disabled state changed');
// Add your post-loading code here (or call the function that contains it)
});
Note that this is extremely hacky. If the author of statecity.js changes their code, this could stop working immediately or could behave unexpectedly.
It is always very risky to rely on tinkering in someone else's code when you have no control over changes to it. Use this solution with caution.
Unfortunately, the original link to the watch extension code seems to have expired, but here it is (not my code but reproduced from author):
// Function to watch for attribute changes
// http://darcyclarke.me/development/detect-attribute-changes-with-jquery
$.fn.watch = function(props, callback, timeout){
if(!timeout)
timeout = 10;
return this.each(function(){
var el = $(this),
func = function(){ __check.call(this, el) },
data = { props: props.split(","),
func: callback,
vals: [] };
$.each(data.props, function(i) { data.vals[i] = el.attr(data.props[i]); });
el.data(data);
if (typeof (this.onpropertychange) == "object"){
el.bind("propertychange", callback);
} else {
setInterval(func, timeout);
}
});
function __check(el) {
var data = el.data(),
changed = false,
temp = "";
for(var i=0;i < data.props.length; i++) {
temp = el.attr(data.props[i]);
if(data.vals[i] != temp){
data.vals[i] = temp;
changed = true;
break;
}
}
if(changed && data.func) {
data.func.call(el, data);
}
}
}

Send event when module was executed

I'm really stuck on this.. I need to send an event when both Load module and Hide module code was executed, and only then send the event. Ideas on how to achieve this?
// Load module
(
function() {
var s=document.createElement('script');
s.type='text/javascript';
s.async=true;
s.src='https://example.com/bundles.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
)();
// Hide module
var inverval = setInterval(hideClass, 100);
function hideClass () {
if ($(".class").hide().length > 0) clearInterval(inverval);
}
// When both happend = Send a event to Google Analytics
DigitalData.push({'event':Module, 'eventLabel':'Page'});
If this is your only option, then perhaps there's something you are going about wrongly. Anyway, let's see ... Only when both events have taken place.
var HandleTwoEvents = function (key1, key2) {
this.count = 0;
this.pack = [];
$self = this;
this.startListening = function(fn) {
fn = fn || function () {}
window.addEventListener(key1, function (ev) {
if ($self.pack.indexOf(key1) < 0) {
$self.pack.push(key1);
$self.count++;
if ($self.count == 2) {
fn();
$self.count = 0;
}
}
console.log(key1, ev);
});
window.addEventListener(key2, function (ev) {
if ($self.pack.indexOf(key2) < 0) {
$self.pack.push(key2);
$self.count++;
if ($self.count == 2) {
fn();
$self.count = 0;
}
}
console.log(key2, ev);
});
}
}
Forgive me, i always use this function to create events
function createEvent(name, obj) {
var evt = document.createEvent("Event");
evt.initEvent(name, true, true);
evt.data = obj;
dispatchEvent(evt);
}
Now, to log both events ...
var both = new HandleTwoEvents("EventKeyOne", "EventKeyTwo");
both.startListening(function () {console.log("This means that both Events have taken place")});
Now, let's test ...
createEvent("EventKeyOne", {});
//key, data are the arguments ... function defined in startListening above does not execute, and upon inspection, both.count is seen to be 1
createEvent("EventKeyTwo", {});
//Now, function executes.
//It also works if "EventKeyTwo" is raised before "EventKeyOne"
Happy Coding!
PS: I'm sure there's a better way to handle the use of the $self variable, with some function binding, i guess. I've never been able to learn it.

I want to not be able to run the same command twice very quickly

So I have this chunk of code here:
lockskipCommand = (function(_super) {
__extends(lockskipCommand, _super);
function lockskipCommand() {
return lockskipCommand.__super__.constructor.apply(this, arguments);
}
lockskipCommand.prototype.init = function() {
this.command = '/lockskip';
this.parseType = 'exact';
return this.rankPrivelege = 'bouncer';
};
lockskipCommand.prototype.functionality = function() {
data.lockBooth();
new ModerationForceSkipService();
return setTimeout((function() {
return data.unlockBooth();
}), 4500);
};
return lockskipCommand;
})(Command);
I want to be able to let it has some sort of cool down, so it can't be used quickly in a row. The reason I want this is to prevent from people being skipped, because that's what this chunk of code is for skipping people.
I hope this is enough information to get some help. Thanks!
You can use Underscore's debounce() method (with true as the third argument).
If you don't want to include Underscore for this simple task, you could do...
var debounceFn = function (fn, delay) {
var lastInvocationTime = Date.now();
delay = delay || 0;
return function () {
(Date.now() - delay > lastInvocationTime) && (lastInvocationTime = Date.now()) && fn && fn();;
};
};
jsFiddle.
What I need is a way to not be able to execute the command more than once in a row.
You could do something similar...
var onceFn = function (fn) {
var invoked = false;
return function () {
! invoked && (invoked = true) && fn && fn();
};
};
jsFiddle.

Javascript this object inside intervals/timeouts

I have a method that is a big setInterval statement, and it needs access to the this object of the object that owns the method from inside the interval. I implemented a simple closure, but it doesn't seem very elegant:
connect: function(to, rate, callback){
var cthis = this, //set cthis to this,
connectIntervalID = setInterval(function(){
if(cthis.attemptConnect(to)){ //reference it here,
clearInterval(connectIntervalID)
cthis.startListening(10) //here,
callback && callback.apply(cthis, []) //and here
}
}, rate)
}
You could also do it with apply or call, if you wanted to use this instead of cthis
connect: function(to, rate, callback){
var cthis = this,
tempFunc = function(){
if(this.attemptConnect(to)){
clearInterval(connectIntervalID)
this.startListening(10)
callback && callback.apply(this, [])
}
}�
connectIntervalID = setInterval(function(){tempFunc.apply(cthis, [])}, rate)
}
However, that seems even worse...
Using a .bind makes it a bit better (in my opinion, you may or may not agree):
support code:
function $A(args){
var out = [];
for(var i=0, l=args.length; i<l; i++){ out.push(args[i]); }
return out;
}
Function.prototype.bind = function() {
var __method = this, args = $A(arguments), object = args.shift();
return function() {
return __method.apply(object || this, args.concat( $A(arguments) ));
};
};
and your code becomes:
connect: function(to, rate, callback){
connectIntervalID = setInterval((function(){
if(this.attemptConnect(to)){ //reference it here,
clearInterval(connectIntervalID)
this.startListening(10) //here,
callback && callback.apply(this, []) //and here
}
}).bind(this), rate)
}
But I'm afraid you won't get a whole lot better.
Your first example is more-or-less the standard way to do this. My only suggestion would be to call your variable something other than cthis; make it descriptive of the object being bound.
Javascript 1.8.5 adds Function.prototype.bind to solve this problem in a different way, but that's not a useful solution for most people.
I'd break out the setInterval function into its own function, attached to the same object as connect. In this way, it will be clear that this refers to the same object:
connect: function (to, rate, callback) {
var obj = this;
var intervalId = setInterval(function () {
obj.connectInterval(intervalId, callback);
}, rate);
},
connectInterval: function (intervalId, callback) {
if (this.attemptConnect(to)) {
clearInterval(intervalId);
this.startListening(10);
callback && callback.apply(this, []);
}
}

JQuery: How to call RESIZE event only once it's FINISHED resizing?

How do I call a function once the browser windows has FINISHED resizing?
I'm trying to do it like so, but am having problems. I'm using the JQuery Resize event function:
$(window).resize(function() {
... // how to call only once the browser has FINISHED resizing?
});
However, this function is called continuously if the user is manually resizing the browser window. Which means, it might call this function dozens of times in short interval of time.
How can I call the resize function only a single time (once the browser window has finished resizing)?
UPDATE
Also without having to use a global variable.
Here is an example using thejh's instructions
You can store a reference id to any setInterval or setTimeout. Like this:
var loop = setInterval(func, 30);
// some time later clear the interval
clearInterval(loop);
Debounce.
function debouncer( func , timeout ) {
var timeoutID , timeout = timeout || 200;
return function () {
var scope = this , args = arguments;
clearTimeout( timeoutID );
timeoutID = setTimeout( function () {
func.apply( scope , Array.prototype.slice.call( args ) );
} , timeout );
}
}
$( window ).resize( debouncer( function ( e ) {
// do stuff
} ) );
Note, you can use this method for anything you want to debounce (key events etc).
Tweak the timeout parameter for optimal desired effect.
You can use setTimeout() and clearTimeout() in conjunction with jQuery.data:
$(window).resize(function() {
clearTimeout($.data(this, 'resizeTimer'));
$.data(this, 'resizeTimer', setTimeout(function() {
//do something
alert("Haven't resized in 200ms!");
}, 200));
});
Update
I wrote an extension to enhance jQuery's default on (& bind)-event-handler. It attaches an event handler function for one or more events to the selected elements if the event was not triggered for a given interval. This is useful if you want to fire a callback only after a delay, like the resize event, or else.
https://github.com/yckart/jquery.unevent.js
;(function ($) {
var methods = { on: $.fn.on, bind: $.fn.bind };
$.each(methods, function(k){
$.fn[k] = function () {
var args = [].slice.call(arguments),
delay = args.pop(),
fn = args.pop(),
timer;
args.push(function () {
var self = this,
arg = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
fn.apply(self, [].slice.call(arg));
}, delay);
});
return methods[k].apply(this, isNaN(delay) ? arguments : args);
};
});
}(jQuery));
Use it like any other on or bind-event handler, except that you can pass an extra parameter as a last:
$(window).on('resize', function(e) {
console.log(e.type + '-event was 200ms not triggered');
}, 200);
http://jsfiddle.net/ARTsinn/EqqHx/
var lightbox_resize = false;
$(window).resize(function() {
console.log(true);
if (lightbox_resize)
clearTimeout(lightbox_resize);
lightbox_resize = setTimeout(function() {
console.log('resize');
}, 500);
});
Just to add to the above, it is common to get unwanted resize events because of scroll bars popping in and out, here is some code to avoid that:
function registerResize(f) {
$(window).resize(function() {
clearTimeout(this.resizeTimeout);
this.resizeTimeout = setTimeout(function() {
var oldOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
var currHeight = $(window).height(),
currWidth = $(window).width();
document.body.style.overflow = oldOverflow;
var prevUndefined = (typeof this.prevHeight === 'undefined' || typeof this.prevWidth === 'undefined');
if (prevUndefined || this.prevHeight !== currHeight || this.prevWidth !== currWidth) {
//console.log('Window size ' + (prevUndefined ? '' : this.prevHeight + "," + this.prevWidth) + " -> " + currHeight + "," + currWidth);
this.prevHeight = currHeight;
this.prevWidth = currWidth;
f(currHeight, currWidth);
}
}, 200);
});
$(window).resize(); // initialize
}
registerResize(function(height, width) {
// this will be called only once per resize regardless of scrollbars changes
});
see jsfiddle
Underscore.js has a couple of great methods for this task: throttle and debounce. Even if you're not using Underscore, take a look at the source of these functions. Here's an example:
var redraw = function() {'redraw logic here'};
var debouncedRedraw = _.debounce(redraw, 750);
$(window).on('resize', debouncedRedraw);
This is my approach:
document.addEventListener('DOMContentLoaded', function(){
var tos = {};
var idi = 0;
var fn = function(id)
{
var len = Object.keys(tos).length;
if(len == 0)
return;
to = tos[id];
delete tos[id];
if(len-1 == 0)
console.log('Resize finished trigger');
};
window.addEventListener('resize', function(){
idi++;
var id = 'id-'+idi;
tos[id] = window.setTimeout(function(){fn(id)}, 500);
});
});
The resize-event-listener catches all incoming resize calls, creates a timeout-function for each and saves the timeout-identifier along with an iterating number prepended by 'id-' (to be usable as array key) in the tos-array.
each time, the timout triggers, it calls the fn-function, that checks, if that was the last timeout in the tos array (the fn-function deletes every executed timout). if true (= if(len-1 == 0)), the resizing is finished.
jQuery provides an off method to remove event handler
$(window).resize(function(){
if(magic == true) {
$(window).off('resize', arguments.callee);
}
});

Categories

Resources