ritardare azioni tra pressione di un tasto in jQuery
Domanda
Come posso ritardare azioni tra pressione dei tasti in jQuery. Per esempio:
Ho qualcosa di simile
if($(this).val().length > 1){
$.post("stuff.php", {nStr: "" + $(this).val() + ""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}else{
$('#suggestions').hide();
}
});
}
Voglio evitare che la pubblicazione dei dati se l'utente continuamente la digitazione. Così come posso dare ritardo .5 secondi?
Soluzione
È possibile utilizzare le capacità di dati di jQuery per fare questo, qualcosa di simile:
$('#mySearch').keyup(function() {
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(search, 500);
$(this).data('timer', wait);
});
function search() {
$.post("stuff.php", {nStr: "" + $('#mySearch').val() + ""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}else{
$('#suggestions').hide();
}
});
}
Il vantaggio principale qui sono le variabili globali in tutto il luogo, e si potrebbe avvolgere questo in una funzione anonima nel setTimeout se si voleva, solo cercando di fare l'esempio più pulito possibile.
Altri suggerimenti
Tutto quello che dovete fare è avvolgere la funzione in un timeout che ottiene ripristinare quando l'utente preme un tasto:
var ref;
var myfunc = function(){
ref = null;
//your code goes here
};
var wrapper = function(){
window.clearTimeout(ref);
ref = window.setTimeout(myfunc, 500);
}
Poi basta invocare "wrapper" nel vostro evento chiave.
C'è un bel plugin per gestire questa situazione. jQuery Throttle / Debounce
La risposta di Nick è perfetto, ma se la manipolazione primo evento immediatamente è critica, allora penso che possiamo fare:
$(selector).keyup(function(e){ //or another event
if($(this).val().length > 1){
if !($.data(this, 'bouncing-locked')) {
$.data(this, 'bouncing-locked', true)
$.post("stuff.php", {nStr: "" + $(this).val() + ""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}else{
$('#suggestions').hide();
}
});
self = this
setTimeout(function() {
$.data(self, 'bouncing-locked', false);
//in case the last event matters, be sure not to miss it
$(this).trigger("keyup"); // call again the source event
}, 500)
}
}
});
Mi piacerebbe avvolgerla in una funzione in questo modo:
var needsDelay = false;
function getSuggestions(var search)
{
if(!needsDelay)
{
needsDelay = true;
setTimeout("needsDelay = false", 500);
if($(this).val().length > 1){
$.post("stuff.php", {nStr: "" + search + ""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}else{
$('#suggestions').hide();
}
});
}
}
}
In questo modo, non importa quante volte si esegue il ping questo, si sarà mai cercare più di ogni 500 millisecondi.