How to make jQuery wait after event - javascript

I have some text boxes that uses AJAX and will process what the user types as they're typing. The problem is that the process that happens after they type is a pretty loaded one. Is there anyway that I can make the event wait 500 msec or so before it will process the event again? So let's say I type a, and then 200ms after I type bsdke. The event will only process a coming in. Let's say I then type asdf 600ms after I typed a. The event will then trigger and process absdkeasdf because it has been 500ms after the last process.
Or even, is there a way I can make the event not become triggered until the previous event that was triggered has finished what it was doing?
Is it possible? Surely sticking a timeout function at the end isn't going to work, right?
$('#selection1-3-4-a, #selection1-3-4-b, #selection1-3-4-c, #selection1-3-4-d, #selection1-3-4-e, #selection1-3-4-f').on('input', function (e) {
var url = "/ex.php";
$.ajax ({
//......
});

It can get hard to tune the event so the users gets a nice experience and you don't flood the server with requests when using autocomplete functions.
I would do it this way:
The event will wait X miliseconds to run itself. If the event is fired again, and the X miliseconds haven't passed, you reset the delay to 0.
Let's be cool and make a generic function to do this (couldn't test it, it might be broken):
function delayedEvent(eventHandler, delay) {
var lastTimeout = null;
return function () {
var that = this,
args= Array.prototype.slice.call(arguments).sort();
if (lastTimeout !== null)
window.clearTimeout(lastTimeout);
lastTimeout = window.setTimeout(function () {
eventHandler.apply(that, args);
}, delay);
};
}
$('... selector ...').on('event', delayedEvent(function () { ... your code ... }, 500));

Use setTimeout:
var timer;
$('#selection1-3-4-a, #selection1-3-4-b, #selection1-3-4-c, #selection1-3-4-d, #selection1-3-4-e, #selection1-3-4-f').on('input', function (e) {
var url = "/ex.php";
clearTimeout(timer);
timer = setTimeout(function() {
$.ajax ({
//......
}, 500);
});

I would recommend using a lock.
// global lock
var locked = false;
$('#selection1-3-4-a, #selection1-3-4-b, #selection1-3-4-c, #selection1-3-4-d, #selection1-3-4-e, #selection1-3-4-f').change(function (e)
{
if(!locked)
{
locked = true;
$.ajax(......) // ajax here
setTimeout(function(){locked = false;}, 500);
}
});

Related

Is there any way to make javascript setTimeout pause when I switch to another tab?

I am having some task that is executing, and when it finishes I show an animation and redirect the user to another page. I am using setTimeout method when redirecting to another page to wait for the whole animation to finish. However, if the user goes to another tab and the event that triggers the animation and redirection fires the user goes back to tab, but doesn't see the animation. Is there any way to tell the setTimeout method to wait until that tab is in active again?
No, but you can capture the timer id you get from setTimeout as well as the clock time you started that timer (e.g. using Date.now()), then call clearTimeout for that id when the document blur event triggers, recording what the remaining time should be based on the current time and the time you saved when you created the timeout, and when the document focus event triggers, start a new timeout with that remaining time as timeout value.
E.g. something like this (but obviously, you want to turn this into something better, with some administrative functions instead of inlining everything)
const timerData = {
interval: DEFAULT_INTERVAL,
start: Date.now(),
id: setTimout(..., DEFAULT_INTERVAL)
};
document.addEventListener(`blur`, () => {
clearTimeout(timerData.id);
timerData.remaining = timerData.start + timerData.interval - Date.now();
});
document.addEventListener(`focus`, () => {
if (timerData.remaining) {
timerData.interval = timerData.remaining
timerData.remaining = undefined;
timerData.start = Date.now();
timerData.id = setTimeout(..., timerData.interval);
}
});
You can create a Timeout class with a start/stop API. Then you can instantiate the class somewhere in your code, and after start or stop it based on user interface events.
Class
class Timeout {
constructor(duration, callback) {
this.duration = duration
this.callback = callback
}
get timeout() { return this._timeout }
set timeout(timeout) { this._timeout = timeout }
get duration() { return this._duration }
set duration(duration) { this._duration = duration }
get callback() { return this._callback }
set callback(callback) { this._callback = callback }
start() {
this.timeout = setTimeout(this.callback, this.duration)
return this
}
stop() {
clearTimeout(this.timeout)
return this
}
}
Instantiation
let timeout = new Timeout(
1000,
() => {
console.log('timeout')
}
)
Start Timeout
timeout.start()
Stop Timeout
timeout.stop()

Javascript sleep until key is pressed

I did some research and found busy wait solutions. I don't want the processor to execute a loop in the script until I get a keypress event through JQuery.
How can I pull of something like sleepUntilKeyPress(), which is a function like sleep() in C but instead of waiting some especific time it waits for a keypress?
You're thinking backwards. Your function shouldn't wait for a keypress to do something, the function should do something whenever a key is pressed. Maintain your data state in a scope that your key callback can reach and update your state on keypress.
You're trying to say:
while(!keypress){
dontDoSomething();
}
You should be doing something more like:
on(keypress, doSomething);
Consider this idea:
var counter, ispressed, el;
// Bad
counter = 0;
ispressed = false;
el = document.getElementById("element");
el.addEventListener("mousedown", function () {
ispressed = true;
});
el.addEventListener("mouseup", function () {
ispressed = false;
});
while (1) {
if (ispressed) {
counter += 1;
}
}
// Better
el.addEventListener("click", function () {
counter += 1;
});
Let's forget about the fact that that while will lock up the program, (I don't even think the event listeners will trigger and I'm pretty sure the DOM will lock up), you're asking your program to waste time constantly checking to see if you're pressed a button yet. Rather than do that, let the browser check for you with the built in addEventListener() and do what you would normally do when you find out that the button has been pressed.
var interval = window.setInterval(function () {
// hang around and do nothing
}, 1000);
document.onkeypress = function () {
if (/* some specific character was pressed */) {
window.clearInterval(interval);
// do some other thing, other thing
}
};

Run JavaScript immediately but wait x seconds before it can be run again?

Im listening for an event and I need to run a function (in this example console log for demoing my code) when it happens.
This is working however the event happens multiple times in quick succession and I only want the function to run once. How can I run the function straight away but then wait a second before its able to be triggered again?
$(document).on('someEvent', function(event, data) {
if (var === 'something') {
console.log('Run');
}
});
Update: To be clear, I need to wait for the event 'someEvent' to occur before my console function runs.
Some like that?
var is_blocked = false;
var block = function( time_to_wait ) {
is_blocked = true;
setTimeout( function() {
is_blocked = false;
}, time_to_wait );
};
$(document).on('someEvent', function(event, data) {
if ( is_blocked === false ) {
block( 1000 );
console.log('Run');
}
});
If you don't mind using an external library, use lodash's debounce method. Note that the sample in the docs is pretty similar to the case you described. The options (leading/trailing) can be used to customize the behavior.
There's a tiny library called underscore.js that has a ton of useful functions. Among these there is _.debounce:
debounce_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function
which will postpone its execution until after wait milliseconds have
elapsed since the last time it was invoked. Useful for implementing
behavior that should only happen after the input has stopped arriving.
For example: rendering a preview of a Markdown comment, recalculating
a layout after the window has stopped being resized, and so on.
Pass true for the immediate argument to cause debounce to trigger the
function on the leading instead of the trailing edge of the wait
interval. Useful in circumstances like preventing accidental
double-clicks on a "submit" button from firing a second time.
In your case it's a matter of wrapping the handler function like this (I used 100ms for the timeout):
$(document).on('someEvent', _.debounce(function(event, data) {
if (var === 'something') {
console.log('Run');
}
}, 100));
Function "functionToBeCalled()" will be executed immediately, and every 0.4 seconds. If you want to call again that function after 0.4s and not every time replace setInterval with setTimeout.
var variable = "something";
$("#button").on('click', function(event, data) {
if ( variable === 'something') {
console.log('Run');
setTimeout(function(){
$("#button").trigger("click");
}, 1000)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button">Button</div>
You could use the current time:
var waitUntil = Date.now();
$(document).on('someEvent', function(event, data) {
if (Date.now() >= waitUntil) {
waitUntil = Date.now() + 5000 // 5 seconds wait from now
console.log('Run');
}
});
Here is a fiddle which uses a button click as the event, and gives feed-back on-screen about whether the event is treated or not.
Here's a neat little function that might help:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args);
};
}

On an event fire a function immediately but wait x seconds untill it is able to run again?

I have an event called customevent. When this event occurs I need to toggle a class on a div.
This is working however the event sometimes fires multiple times in quick succession. When this happens the class is added and removed again which is not what I want.
$(document).on('customevent', function(event, data) {
$('.class').toggleClass('toggle-class');
});
When the event occurs I need the class to be immediately toggled. However I need the class to not be able to be toggled for 1 second even if the event continues to fire. The following is not working.
var is_blocked;
$(document).on('customevent', function(event, data) {
if (is_blocked !== true) {
$('.class').toggleClass('toggle-class');
is_blocked = true;
setTimeout(function(){
is_blocked = false;
}, 1000);
}
});
Why not set is_blocked to a timestamp rather than a boolean? Something like:
var blocked_time = 0;
$(document).on('customevent', function(event, data) {
if (blocked_time + 1000 < new Date().getTime()) {
$('.class').toggleClass('toggle-class');
blocked_time = new Date().getTime();
}
});
You are very close, but no sigar
var is_blocked = false;
$(document).on('customevent', function(event, data) {
if (!is_blocked) {
$('.class').toggleClass('toggle-class');
is_blocked = true;
setTimeout(function(){
is_blocked = false;
}, 1000);
}
is_blocked = true;
//I'll be set to true, and in a second ill be false
//thanks to the timeout. This might not be a stable solution
//because what happens if the function is spammed for over a second?
});
You need to set is_blocked to true every time the function runs independent of the if-statement.
You might want to look at the debounce (or throttle in lodash) function, which might be used like this
var throttled = debounce(function() {
// your actions will be executed at max
// once every 1000ms
}, 1000);
$(document).on('event', throttled);
On the subject: https://davidwalsh.name/javascript-debounce-function

How to delay the .keyup() handler until the user stops typing?

I’ve got a search field. Right now it searches for every keyup. So if someone types “Windows”, it will make a search with AJAX for every keyup: “W”, “Wi”, “Win”, “Wind”, “Windo”, “Window”, “Windows”.
I want to have a delay, so it only searches when the user stops typing for 200 ms.
There is no option for this in the keyup function, and I have tried setTimeout, but it didn’t work.
How can I do that?
I use this small function for the same purpose, executing a function after the user has stopped typing for a specified amount of time or in events that fire at a high rate, like resize:
function delay(callback, ms) {
var timer = 0;
return function() {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
// Example usage:
$('#input').keyup(delay(function (e) {
console.log('Time elapsed!', this.value);
}, 500));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="input">Try it:
<input id="input" type="text" placeholder="Type something here..."/>
</label>
How it works:
The delay function will return a wrapped function that internally handles an individual timer, in each execution the timer is restarted with the time delay provided, if multiple executions occur before this time passes, the timer will just reset and start again.
When the timer finally ends, the callback function is executed, passing the original context and arguments (in this example, the jQuery's event object, and the DOM element as this).
UPDATE 2019-05-16
I have re-implemented the function using ES5 and ES6 features for modern environments:
function delay(fn, ms) {
let timer = 0
return function(...args) {
clearTimeout(timer)
timer = setTimeout(fn.bind(this, ...args), ms || 0)
}
}
The implementation is covered with a set of tests.
For something more sophisticated, give a look to the jQuery Typewatch plugin.
If you want to search after the type is done use a global variable to hold the timeout returned from your setTimout call and cancel it with a clearTimeout if it hasn't yet happend so that it won't fire the timeout except on the last keyup event
var globalTimeout = null;
$('#id').keyup(function(){
if(globalTimeout != null) clearTimeout(globalTimeout);
globalTimeout =setTimeout(SearchFunc,200);
}
function SearchFunc(){
globalTimeout = null;
//ajax code
}
Or with an anonymous function :
var globalTimeout = null;
$('#id').keyup(function() {
if (globalTimeout != null) {
clearTimeout(globalTimeout);
}
globalTimeout = setTimeout(function() {
globalTimeout = null;
//ajax code
}, 200);
}
Another slight enhancement on CMS's answer. To easily allow for separate delays, you can use the following:
function makeDelay(ms) {
var timer = 0;
return function(callback){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
};
If you want to reuse the same delay, just do
var delay = makeDelay(250);
$(selector1).on('keyup', function() {delay(someCallback);});
$(selector2).on('keyup', function() {delay(someCallback);});
If you want separate delays, you can do
$(selector1).on('keyup', function() {makeDelay(250)(someCallback);});
$(selector2).on('keyup', function() {makeDelay(250)(someCallback);});
You could also look at underscore.js, which provides utility methods like debounce:
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
Explanation
Use a variable to store the timeout function. Then use clearTimeout() to clear this variable of any active timeout functions, and then use setTimeout() to set the active timeout function again. We run clearTimeout() first, because if a user is typing "hello", we want our function to run shortly after the user presses the "o" key (and not once for each letter).
Working Demo
Super simple approach, designed to run a function after a user has finished typing in a text field...
$(document).ready(function(e) {
var timeout;
var delay = 2000; // 2 seconds
$('.text-input').keyup(function(e) {
$('#status').html("User started typing!");
if(timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
myFunction();
}, delay);
});
function myFunction() {
$('#status').html("Executing function for user!");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Status: <span id="status">Default Status</span><br>
<textarea name="text-input" class="text-input"></textarea>
Based on the answer of CMS, I made this :
Put the code below after include jQuery :
/*
* delayKeyup
* http://code.azerti.net/javascript/jquery/delaykeyup.htm
* Inspired by CMS in this post : http://stackoverflow.com/questions/1909441/jquery-keyup-delay
* Written by Gaten
* Exemple : $("#input").delayKeyup(function(){ alert("5 secondes passed from the last event keyup."); }, 5000);
*/
(function ($) {
$.fn.delayKeyup = function(callback, ms){
var timer = 0;
$(this).keyup(function(){
clearTimeout (timer);
timer = setTimeout(callback, ms);
});
return $(this);
};
})(jQuery);
And simply use like this :
$('#input').delayKeyup(function(){ alert("5 secondes passed from the last event keyup."); }, 5000);
Careful : the $(this) variable in the function passed as a parameter does not match input
jQuery:
var timeout = null;
$('#input').keyup(function() {
clearTimeout(timeout);
timeout = setTimeout(() => {
console.log($(this).val());
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type="text" id="input" placeholder="Type here..."/>
Pure Javascript:
let input = document.getElementById('input');
let timeout = null;
input.addEventListener('keyup', function (e) {
clearTimeout(timeout);
timeout = setTimeout(function () {
console.log('Value:', input.value);
}, 1000);
});
<input type="text" id="input" placeholder="Type here..."/>
Delay Multi Function Calls using Labels
This is the solution i work with. It will delay the execution on ANY function you want. It can be the keydown search query, maybe the quick click on previous or next buttons ( that would otherwise send multiple request if quickly clicked continuously , and be not used after all). This uses a global object that stores each execution time, and compares it with the most current request.
So the result is that only that last click / action will actually be called, because those requests are stored in a queue, that after the X milliseconds is called if no other request with the same label exists in the queue!
function delay_method(label,callback,time){
if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}
delayed_methods[label]=Date.now();
var t=delayed_methods[label];
setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{ delayed_methods[label]=""; callback();}}, time||500);
}
You can set your own delay time ( its optional, defaults to 500ms). And send your function arguments in a "closure fashion".
For example if you want to call the bellow function:
function send_ajax(id){console.log(id);}
To prevent multiple send_ajax requests, you delay them using:
delay_method( "check date", function(){ send_ajax(2); } ,600);
Every request that uses the label "check date" will only be triggered if no other request is made in the 600 miliseconds timeframe. This argument is optional
Label independency (calling the same target function) but run both:
delay_method("check date parallel", function(){send_ajax(2);});
delay_method("check date", function(){send_ajax(2);});
Results in calling the same function but delay them independently because of their labels being different
If someone like to delay the same function, and without external variable he can use the next script:
function MyFunction() {
//Delaying the function execute
if (this.timer) {
window.clearTimeout(this.timer);
}
this.timer = window.setTimeout(function() {
//Execute the function code here...
}, 500);
}
This function extends the function from Gaten's answer a bit in order to get the element back:
$.fn.delayKeyup = function(callback, ms){
var timer = 0;
var el = $(this);
$(this).keyup(function(){
clearTimeout (timer);
timer = setTimeout(function(){
callback(el)
}, ms);
});
return $(this);
};
$('#input').delayKeyup(function(el){
//alert(el.val());
// Here I need the input element (value for ajax call) for further process
},1000);
http://jsfiddle.net/Us9bu/2/
I'm surprised that nobody mention the problem with multiple input in CMS's very nice snipped.
Basically, you would have to define delay variable individually for each input. Otherwise if sb put text to first input and quickly jump to other input and start typing, callback for the first one WON'T be called!
See the code below I came with based on other answers:
(function($) {
/**
* KeyUp with delay event setup
*
* #link http://stackoverflow.com/questions/1909441/jquery-keyup-delay#answer-12581187
* #param function callback
* #param int ms
*/
$.fn.delayKeyup = function(callback, ms){
$(this).keyup(function( event ){
var srcEl = event.currentTarget;
if( srcEl.delayTimer )
clearTimeout (srcEl.delayTimer );
srcEl.delayTimer = setTimeout(function(){ callback( $(srcEl) ); }, ms);
});
return $(this);
};
})(jQuery);
This solution keeps setTimeout reference within input's delayTimer variable. It also passes reference of element to callback as fazzyx suggested.
Tested in IE6, 8(comp - 7), 8 and Opera 12.11.
This worked for me where I delay the search logic operation and make a check if the value is same as entered in text field. If value is same then I go ahead and perform the operation for the data related to search value.
$('#searchText').on('keyup',function () {
var searchValue = $(this).val();
setTimeout(function(){
if(searchValue == $('#searchText').val() && searchValue != null && searchValue != "") {
// logic to fetch data based on searchValue
}
else if(searchValue == ''){
// logic to load all the data
}
},300);
});
Delay function to call up on every keyup.
jQuery 1.7.1 or up required
jQuery.fn.keyupDelay = function( cb, delay ){
if(delay == null){
delay = 400;
}
var timer = 0;
return $(this).on('keyup',function(){
clearTimeout(timer);
timer = setTimeout( cb , delay );
});
}
Usage: $('#searchBox').keyupDelay( cb );
From ES6, one can use arrow function syntax as well.
In this example, the code delays keyup event for 400ms after users finish typeing before calling searchFunc make a query request.
const searchbar = document.getElementById('searchBar');
const searchFunc = // any function
// wait ms (milliseconds) after user stops typing to execute func
const delayKeyUp = (() => {
let timer = null;
const delay = (func, ms) => {
timer ? clearTimeout(timer): null
timer = setTimeout(func, ms)
}
return delay
})();
searchbar.addEventListener('keyup', (e) => {
const query = e.target.value;
delayKeyUp(() => {searchFunc(query)}, 400);
})
Updated Typescript version:
const delayKeyUp = (() => {
let timer: NodeJS.Timeout;
return (func: Function, ms: number) => {
timer ? clearTimeout(timer) : null;
timer = setTimeout(() => func(), ms);
};
})();
This is a solution along the lines of CMS's, but solves a few key issues for me:
Supports multiple inputs, delays can run concurrently.
Ignores key events that didn't changed the value (like Ctrl, Alt+Tab).
Solves a race condition (when the callback is executed and the value already changed).
var delay = (function() {
var timer = {}
, values = {}
return function(el) {
var id = el.form.id + '.' + el.name
return {
enqueue: function(ms, cb) {
if (values[id] == el.value) return
if (!el.value) return
var original = values[id] = el.value
clearTimeout(timer[id])
timer[id] = setTimeout(function() {
if (original != el.value) return // solves race condition
cb.apply(el)
}, ms)
}
}
}
}())
Usage:
signup.key.addEventListener('keyup', function() {
delay(this).enqueue(300, function() {
console.log(this.value)
})
})
The code is written in a style I enjoy, you may need to add a bunch of semicolons.
Things to keep in mind:
A unique id is generated based on the form id and input name, so they must be defined and unique, or you could adjust it to your situation.
delay returns an object that's easy to extend for your own needs.
The original element used for delay is bound to the callback, so this works as expected (like in the example).
Empty value is ignored in the second validation.
Watch out for enqueue, it expects milliseconds first, I prefer that, but you may want to switch the parameters to match setTimeout.
The solution I use adds another level of complexity, allowing you to cancel execution, for example, but this is a good base to build on.
Combining CMS answer with Miguel's one yields a robust solution allowing concurrent delays.
var delay = (function(){
var timers = {};
return function (callback, ms, label) {
label = label || 'defaultTimer';
clearTimeout(timers[label] || 0);
timers[label] = setTimeout(callback, ms);
};
})();
When you need to delay different actions independently, use the third argument.
$('input.group1').keyup(function() {
delay(function(){
alert('Time elapsed!');
}, 1000, 'firstAction');
});
$('input.group2').keyup(function() {
delay(function(){
alert('Time elapsed!');
}, 1000, '2ndAction');
});
Building upon CMS's answer here's new delay method which preserves 'this' in its usage:
var delay = (function(){
var timer = 0;
return function(callback, ms, that){
clearTimeout (timer);
timer = setTimeout(callback.bind(that), ms);
};
})();
Usage:
$('input').keyup(function() {
delay(function(){
alert('Time elapsed!');
}, 1000, this);
});
If you want to do something after a period of time and reset that timer after a specific event like keyup, the best solution is made with clearTimeout and setTimeout methods:
// declare the timeout variable out of the event listener or in the global scope
var timeout = null;
$(".some-class-or-selector-to-bind-event").keyup(function() {
clearTimeout(timout); // this will clear the recursive unneccessary calls
timeout = setTimeout(() => {
// do something: send an ajax or call a function here
}, 2000);
// wait two seconds
});
Use
mytimeout = setTimeout( expression, timeout );
where expression is the script to run and timeout is the time to wait in milliseconds before it runs - this does NOT hault the script, but simply delays execution of that part until the timeout is done.
clearTimeout(mytimeout);
will reset/clear the timeout so it does not run the script in expression (like a cancel) as long as it has not yet been executed.
Based on the answer of CMS, it just ignores the key events that doesn't change value.
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
var duplicateFilter=(function(){
var lastContent;
return function(content,callback){
content=$.trim(content);
if(content!=lastContent){
callback(content);
}
lastContent=content;
};
})();
$("#some-input").on("keyup",function(ev){
var self=this;
delay(function(){
duplicateFilter($(self).val(),function(c){
//do sth...
console.log(c);
});
}, 1000 );
})
User lodash javascript library and use _.debounce function
changeName: _.debounce(function (val) {
console.log(val)
}, 1000)
Use the bindWithDelay jQuery plugin:
element.bindWithDelay(eventType, [ eventData ], handler(eventObject), timeout, throttle)
var globalTimeout = null;
$('#search').keyup(function(){
if(globalTimeout != null) clearTimeout(globalTimeout);
globalTimeout =setTimeout(SearchFunc,200);
});
function SearchFunc(){
globalTimeout = null;
console.log('Search: '+$('#search').val());
//ajax code
};
Here is a suggestion I have written that takes care of multiple input in your form.
This function gets the Object of the input field, put in your code
function fieldKeyup(obj){
// what you want this to do
} // fieldKeyup
This is the actual delayCall function, takes care of multiple input fields
function delayCall(obj,ms,fn){
return $(obj).each(function(){
if ( typeof this.timer == 'undefined' ) {
// Define an array to keep track of all fields needed delays
// This is in order to make this a multiple delay handling
function
this.timer = new Array();
}
var obj = this;
if (this.timer[obj.id]){
clearTimeout(this.timer[obj.id]);
delete(this.timer[obj.id]);
}
this.timer[obj.id] = setTimeout(function(){
fn(obj);}, ms);
});
}; // delayCall
Usage:
$("#username").on("keyup",function(){
delayCall($(this),500,fieldKeyup);
});
Take a look at the autocomplete plugin. I know that it allows you to specify a delay or a minimum number of characters. Even if you don't end up using the plugin, looking through the code will give you some ideas on how to implement it yourself.
Well, i also made a piece of code for limit high frequency ajax request cause by Keyup / Keydown. Check this out:
https://github.com/raincious/jQueue
Do your query like this:
var q = new jQueue(function(type, name, callback) {
return $.post("/api/account/user_existed/", {Method: type, Value: name}).done(callback);
}, 'Flush', 1500); // Make sure use Flush mode.
And bind event like this:
$('#field-username').keyup(function() {
q.run('Username', this.val(), function() { /* calling back */ });
});
Saw this today a little late but just want to put this here in case someone else needed. just separate the function to make it reusable. the code below will wait 1/2 second after typing stop.
var timeOutVar
$(selector).on('keyup', function() {
clearTimeout(timeOutVar);
timeOutVar= setTimeout(function(){ console.log("Hello"); }, 500);
});
// Get an global variable isApiCallingInProgress
// check isApiCallingInProgress
if (!isApiCallingInProgress) {
// set it to isApiCallingInProgress true
isApiCallingInProgress = true;
// set timeout
setTimeout(() => {
// Api call will go here
// then set variable again as false
isApiCallingInProgress = false;
}, 1000);
}

Categories