Alert JavaScript with Timer


How can I create an Alert in JavaScript that can be seen for 2 seconds and then close automatically (only) without the user clicking accept?

asked by Efrain Mejias C 23.08.2016 в 22:31

6 answers


I do it with the setTimeout function. In the following way.

  setTimeout(function() {
answered by 24.08.2016 / 00:21

I present you with Toastr , is a library in JavaScript that generates notifications in a " modern ":

toastr.options = {
  "debug": false,
  "positionClass": "toast-bottom-right",
  "onclick": null,
  "fadeIn": 300,
  "fadeOut": 100,
  "timeOut": 5000,
  "extendedTimeOut": 1000

var showToastrs = false;

function toastrs() {
  if (!showToastrs) {
    toastr.error('Estamos bajo ataque DDoS', 'Error Critico!');
    toastr.success('Se guardaron los cambios satisfactoriamente', 'Todo en orden');
    toastr.warning('La latencia del server esta aumentando.', 'Alerta!');
  } else {
    toastr.error('no se puede!\'t.', 'Otro error crítico');

// Definimos los callback cuando el TOAST le da un fade in/out:
toastr.options.onFadeIn = function() {
  showToastrs = true;
toastr.options.onFadeOut = function() {
  showToastrs = false;

$(function() {
  $("#clear").on("click", function() {
    // Clears the current list of toasts
  $("#rewind").on("click", function() {
    // show toastrs :)
<script src=""></script>
<script src=""></script>
<link href="" rel="stylesheet"/>
<link href="" rel="stylesheet"/>
<a href="" target="_blank">Toastr official demo</a>
<input id="clear" type="submit" value="Limpiar notificaciones">
<input id="rewind" type="submit" value="Mostrar notificaciones">
answered by 23.08.2016 в 23:11

I see that you want to open and close the message, with Javascript this can not be done, closing the message has to be manually.

Another option is to show a window with the message and close it automatically after 2 seconds (2000 ms).


<p>Abre un mensaje que se cerrara en 2 segundos.</p>

<button onclick="ejecutaAlerta()">muestra mensaje</button>

function ejecutaAlerta() {   
var w ='','','width=100,height=100')
w.document.write('Hola StackOverflow!')
setTimeout(function() {w.close();}, 2000)


Whoever calls the function is the setTimeOut () method:


setTimeout () Perform a function, after waiting for a number   specific milliseconds.

answered by 24.08.2016 в 00:45

Another option that can help you is JQuery jGrowl

I'll give you an example with a duration of 2 seconds:

$.jGrowl("Hello world!",{ life : 2000});
<script src=""></script>
<link rel="stylesheet" type="text/css" href="//" />
<script src="//"></script>

If you need something more "modern" I recommend toastr

answered by 24.08.2016 в 01:47

I like the solution of @fredyfx but if you care about the upload speed and the resources used by your app you can implement something similar in fewer bytes by only putting the functions you are going to use.

This is an example, of course the styles can be adjusted to the aesthetics of your application and you can add more features. This is a base for writing your own component without having to load long libraries that result in heavy applications.

(function(window, document) { // asilamos el componente
  // creamos el contedor de las tostadas o la tostadora
  var container = document.createElement('div');
  container.className = 'toast-container';
  // esta es la funcion que hace la tostada
  window.doToast = function(message) {
    // creamos tostada
    var toast = document.createElement('div');
    toast.className = 'toast-toast';
    toast.innerHTML = message;

    // agregamos a la tostadora

    // programamos su eliminación
    setTimeout(function() {
      // cuando acabe de desaparecer, lo eliminamos del dom.
      toast.addEventListener("transitionend", function() {
      }, false);

      // agregamos un estilo que inicie la "transition". 
    }, 2000); // OP dijo, "solo dos segundos"
})(window, document);

// ejempo de uso
doToast("Hola mundo!");

// ejemplo retardado de uso
setTimeout(function() {
   doToast("Soy una tostada");
}, 1200);
.toast-container {
  position: fixed;
  width: 150px;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 10; /* sobre todo lo demás */

.toast-toast {
  font-size: 250%;
  margin-bottom: 3px;
  border-radius: 2px;
  border: 1px green;
  background: #98FF98;
  text-align: center;
  line-height: 1;  
  transition: all 0.5s; 

  opacity: 0;
answered by 24.08.2016 в 03:42

With the standard javascript alert I doubt you can do it, but if you use an alert implemented from jquery as being


You will see in the example that you implement a timer , for example the title Alert Dialogs define

$.alert('jqAlert is easy to use with alerts and its where I got my start.', {
    title:'Alert Title Message',
    exception: 'Exception',
    stack: 'Stack Trace',
    onTimeout:function() { },
    onClose: function() { },
            title:'Press Me',
            callback:function() { $(this).dialog("close");}

You will see the% co_of% after that time it closes only

answered by 23.08.2016 в 22:37