Mick Mick - 25 days ago 10
jQuery Question

SweetAlert2 execute function after timer

What am I doing wrong here?

swal({
title: "Done.",
text: "Labels Printed.",
timer: 1000,
type: "success",
showConfirmButton: false

}).then(function () {

alert('done');

});


The alert is not getting fired, do I need to catch 'timer' somehow? (The alert is just an example, I am actually clearing my form here.)

Also how do I get rid of the textLabels:1 Uncaught (in promise) timer error?

I was using
.done()


Can someone add the tag for SweetAlert2? I don't have the reputation to do it.

Mick

What do I need to do when I don't want anything to happen after?:

swal({
title: "Error.",
text: "Authorisation Failed.",
timer: 1000,
type: "error",
showConfirmButton: false
}).then(
function() {}

)

Answer

SweetAlert2 uses promises. Each promise can be resolved or rejected and you handling it this way:

swal(…).then(
  function () {
    // handle resolve (confirm button)
  }, 
  function (dismiss) {
    // handle reject, dismiss can be  'cancel', 'overlay', 'close', and 'timer'
  }
)

Closing a modal by timer considered as a promise rejection, so you should handle it like this:

swal({
  title: 'Auto close alert!',
  text: 'I will close in 2 seconds.',
  timer: 2000
}).then(
  function() {}, 
  function() {
    alert('done');
  }
)
<script src="https://cdn.jsdelivr.net/sweetalert2/6.0.0/sweetalert2.js"></script>
<link href="https://cdn.jsdelivr.net/sweetalert2/6.0.0/sweetalert2.css" rel="stylesheet"/>

Example: https://limonte.github.io/sweetalert2/#dismiss-handle

Docs: https://github.com/limonte/sweetalert2#handling-dismissals

Comments