甜蜜的警报。在警告框中显示倒计时

Sweet alert. Display countdown in alert box

我在 sweetalert 消息中显示倒计时时遇到问题。单击后我使用 "A message with auto close timer"。我希望倒计时出现在消息中,用户可以看到倒计时。

swal({  
    title: "Please w8 !",
    text: "Data loading...",
    timer: 10000,
    showConfirmButton: false 
});

SweetAlert 是做不到的。它不支持计数 UI。但永远不要说永远:-)

我准备了一个小技巧,可以帮助你做到这一点。只需将下面的代码添加到您的应用程序中,您就会看到实时计数机制。并且不要忘记也添加 jQuery。

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);

结果:

这是更好的解决方案

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);
    }
})();