Search code examples
javascriptalertsweetalertsweetalert2

Sweetalert delay popup from opening


I am trying to delay a SweetAlert popup to not display for a few seconds once it has been triggered.

e.g. User performs action on webpage to trigger SweetAlert, but instead of displaying instantly, it wait 2 seconds and then displays. - I've been researching various ways to do this, but no luck...I think maybe setTimeout is needed?

Here is my SweetAlert function which is working so far:

if( response == 10 ){
    swal({
      type: 'success',
      title: 'YOUR BALANCED BOX IS FULL',
      text: 'Youve added the recommended amount of items for your plan!',
      allowOutsideClick: false,
      showCancelButton: true,
      cancelButtonText: "Modify Selection",
      cancelButtonColor: '#d33',
      showConfirmButton: true,
      confirmButtonColor: '#61ce70',
      confirmButtonText: "Proceed To Cart",
    }).then((result) => {
        if (result.value) {
            window.location = "/basket/";
        }
    }) 
}

Any help appreciated!


Solution

  • Yes indeed you can use setTimeout to achieve this easily, i set up a simple snippet so you can try it out!

    // When button gets clicked.
    $("#button").click(() => {
    	// Instantely change it's text to loading..
    	$("#button").text("Loading!");
      // Wait 2kms then change the text to Done!
    	setTimeout(() => {
      	$("#button").text("Done!");
      }, 2000);
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="button">Event</button>

    -Leo