Borrar mensaje jQuery delay setTimeout

How could I clear the field message after a couple seconds using delay jQuery function instead of setTimeout? The code below will clear value immediately.

    var $this = $(this),
            mid = $this.find("#emid"),
            contents = $this.find("#equestion");    

    if(contents.length<30){
      contents.css('color','red')
      .val('Error Message')
      .delay(5000)
      .val('');
      }

preguntado el 09 de marzo de 12 a las 16:03

setTimeout is the neatest option here. -

No puedes. .delay is for animations; setTimeout is basically for everything else. I'm sure .delay usos setTimeout internally as well. -

3 Respuestas

UPD: Actually, you can simply use the default queue and freely chain effects (like show) and non-effects (like val). Just wrap the latter in a queue-dequeue llamada:

$("input")
    .queue(function() { $(this).val("blah").dequeue() })
    .delay(1000)
    .queue(function() { $(this).val("").dequeue() })
    .fadeOut(1000) // etc

http://jsfiddle.net/cA4jB/1/

/UPD

No, you don't have to (and actually shouldn't) use setTimeout. jQuery provides a nice built-in mechanism for this, called cola. The basic idea is like this: you "collect" functions or delays in a named queue:

 $(elem).queue("queueName", function(next) { do something and call next() });
 $(elem).queue("queueName", function(next) { do something else and call next() });
 $(elem).delay(3000, "queueName");
 $(elem).queue("queueName", function(next) { do something else and call next() });

y luego llamar dequeue() to start processing:

 $(elem).dequeue("queueName")

Each function in the queue is called one after another, and delays work as expected.

En la acción: http://jsfiddle.net/cA4jB/

respondido 11 mar '12, 11:03

Interesting. I like this a lot, makes sense, Thank you. - códice73

@Codex73: actually, the solution is even simpler. I updated the post. - Georg

jQuery documentation clearly mentions that

El método .delay () es mejor para retrasar entre los efectos de jQuery en cola. Debido a que es limitado (por ejemplo, no ofrece una forma de cancelar el retraso) .delay () no reemplaza la función nativa setTimeout de JavaScript, que puede ser más apropiada para ciertos casos de uso.

http://api.jquery.com/delay/

So, its better to use the setTimeout function

https://developer.mozilla.org/en/DOM/window.setTimeout

respondido 09 mar '12, 16:03

It's a bit tricky, but you can create an animation that does almost nothing, with a callback that yould clear the value.

if(contents.length<30){
    contents.css('color','red')
        .val('Error Message').animate({
            opacity: 1
        }, 5000, function() {
            contents.val('');
        });
}

The best way is still to use setTimeout

respondido 09 mar '12, 16:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.