JavaScript Alert with timer

How can I do to create an Alert in JavaScript that looks for 2 seconds and then automatically closes (only) without the user clicking Ok?

 8
Author: Efrain Mejias C, 2016-08-23

6 answers

I do it with the setTimeout function. As follows.

$('#alert').fadeIn();     
  setTimeout(function() {
       $("#alert").fadeOut();           
  },2000);
 4
Author: Yami, 2016-08-23 22:21:34

I introduce you to Toastr, it is a library in JavaScript that generates notifications in a modern " Way":

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
    toastr.clear();
  });
  $("#rewind").on("click", function() {
    // show toastrs :)
    toastrs();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://codeseven.github.com/toastr/toastr.js"></script>
<link href="http://codeseven.github.com/toastr/toastr.css" rel="stylesheet"/>
<link href="http://codeseven.github.com/toastr/toastr-responsive.css" rel="stylesheet"/>
<a href="http://codeseven.github.io/toastr/demo.html" target="_blank">Toastr official demo</a>
<br/>
<br/>
<input id="clear" type="submit" value="Limpiar notificaciones">
<input id="rewind" type="submit" value="Mostrar notificaciones">
 6
Author: fredyfx, 2016-08-23 21:11:46

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

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

<html>
<body>

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

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

<script>
function ejecutaAlerta() {   
var w = window.open('','','width=100,height=100')
w.document.write('Hola StackOverflow!')
w.focus()
setTimeout(function() {w.close();}, 2000)
}
</script>

</body>
</html>

Who calls the function is the method setTimeOut():

SetTimeout () executes a function, after waiting for a number specific of millisecond.

 4
Author: Jorgesys, 2016-08-24 02:39:57

Another option that may serve you is JQuery jGrowl

I leave you an example with a duration of 2 seconds:

$.jGrowl("Hello world!",{ life : 2000});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.1/jquery.jgrowl.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.1/jquery.jgrowl.min.js"></script>

If you require something more "modern" I recommend toastr

 3
Author: JuankGlezz, 2017-04-13 13:00:52

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

This is an example, of course you can adjust the styles to the aesthetics of your application and you can add more features. This is a foundation 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';
  document.body.appendChild(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
    container.appendChild(toast);    

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

      // agregamos un estilo que inicie la "transition". 
      toast.classList.add("fadeout");      
    }, 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; 
}

.fadeout{
  opacity: 0;
}
 3
Author: rnrneverdies, 2016-08-24 01:53:39

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

JqAlert

You will see in the example to 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',
    icon:'',
    customIcon:'icon-asterisk',
    exception: 'Exception',
    stack: 'Stack Trace',
    timer:5000,
    onTimeout:function() { },
    onClose: function() { },
    buttons:[
        {
            title:'Press Me',
            callback:function() { $(this).dialog("close");}
        }
    ]
});

You will see the timer:5000 after that time closes only

 2
Author: Leandro Tuttini, 2016-08-23 20:37:44