Search code examples
javascriptalertsweetalertsweetalert2

How to add timer after sweetalert2 open?


I want to add timer after callback another function in Sweetalert2. In the example just add timer when swal run.

this is basic code :

swal({
  title: 'alert!',
  text: 'I need this close after my function',
})

and below is ajax and I need the swal close in second after ajax success

$.ajax({
    dataType: "json",
    url: url,
    type: "GET",
    data: {some: data},
    success: function (json) {
        if (json.status === 'OK') {
            swal({
                timer:2000
            });
        }
    }
});

but when ajax success, new modal of swal() opened with timer, not close the current swal()


Solution

  • This is inpired by answer From Gaurav Chaudhary. Id modified with standard of swal doc. I publish this because he not accept my edit.

    //if(swal.isVisible()) { // uncomment to check if modal swal visible
        setTimeout(function(){
            swal.closeModal();
         }, 2000);
    //}
    
    
    swal('Any fool can use a computer')
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/sweetalert2/6.6.0/sweetalert2.min.css">
    <script src="https://cdn.jsdelivr.net/sweetalert2/6.6.0/sweetalert2.min.js"></script>