5

I have an issue with displaying the countdown in sweetalert message. After click i use the "A message with auto close timer". I want that countdown to be in the message and user can see the countdown.

swal({  
    title: "Please w8 !",
    text: "Data loading...",
    timer: 10000,
    showConfirmButton: false 
});
michaPau
  • 1,598
  • 18
  • 24
Filip Martiak
  • 85
  • 1
  • 6
  • I don't think it is possible without changing the library. Perhaps [this answer to a similar question](http://stackoverflow.com/questions/35718899/countdown-in-setinterval-function-with-sweet-alert-plugin) can work for you. – michaPau Apr 27 '16 at 12:12
  • 1
    See my answer. You will find complete solution (: – Ali Mamedov Apr 27 '16 at 12:13

2 Answers2

19

It is impossible to do with SweetAlert. It doesn't support counting on UI. But never say never :-)

I have prepared a little hack, which can help you to do that. Just add the code below to your application, and you will see live counting mechanism. And don't forget to add jQuery too.

var
    closeInSeconds = 5,
    displayText = "I will close in #1 seconds.",
    timer;

swal({
    title: "Auto close alert!",   
    text: displayText.replace(/#1/, closeInSeconds),   
    timer: closeInSeconds * 1000,   
    showConfirmButton: false 
});

timer = setInterval(function() {

    closeInSeconds--;

    if (closeInSeconds < 0) {

        clearInterval(timer);
    }

    $('.sweet-alert > p').text(displayText.replace(/#1/, closeInSeconds));

}, 1000);

Result:

enter image description here

Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47
6

Here is better solution

var timer = 10, // timer in seconds
    isTimerStarted = false;

(function customSwal() {
    swal({  
        title: "Please w8 !",
        text: "Data loading..." + timer,
        timer: !isTimerStarted ? timer * 1000 : undefined,
        showConfirmButton: false
    });
    isTimerStarted = true;
    if(timer) {
        timer--;
        setTimeout(customSwal, 1000);
    }
})();
Andrey Etumyan
  • 1,394
  • 11
  • 17