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");    

      .val('Error Message')

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:

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


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:


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

En la acción:

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.

So, its better to use the setTimeout function

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.

        .val('Error Message').animate({
            opacity: 1
        }, 5000, function() {

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.