sweetalert2取消计时器/超时

时间:2018-12-04 23:01:29

标签: javascript timer modal-dialog sweetalert2

我想在5秒后使用SweetAlert2做一个可取消的自动关闭模式,但是我找不到停止计时器的方法,请帮忙!这是js代码:

$(document).on('click', '#view_more_trigger', function(e) { 
    e.preventDefault();
    var div = document.getElementById('view_more');
    div.style.display = div.style.display == 'none' ? 'block' : 'none';
    $(this).html( div.style.display == 'none' ? "View Moar" : "View Less");
});

var closeInSeconds=10,
    timerInterval;

var my_swal = swal({
    type:   'success',
    html:   '<div id="view_more" style="display: none;">'+
                $('#details').html() +
            '</div>'+
            '<a href="javascript:;" id="view_more_trigger" >View more</a>'+
            '<p id="show_timeout" style="display: none;"></p>',
    timer: closeInSeconds * 1000,

    onOpen: () => {

        $('#show_timeout').show();
        timerInterval = setInterval(function() {

            $(document).on('click', '#view_more_trigger', function(e) { 
                e.preventDefault();

                console.log('trying desperately to cancel the damn timer!');
                //swal.stop();                //  error, function !exists
                //my_swal.timeout.stop();     //  Cannot read property 'stop' of undefined
                //my_swal.timer.stop();       //  Cannot read property 'stop' of undefined


                // ..or to increase it
                if(closeInSeconds<1000) {
                    console.log('incrementing closeInSeconds by 1000');
                    closeInSeconds +=1000;
                }
                //swal.timer = closeInSeconds * 1000;

                swal.timer = closeInSeconds * 1000;
                my_swal.timer = closeInSeconds * 1000;

                clearInterval(timerInterval);
            });

            closeInSeconds--;
            if (closeInSeconds < 0) {
                clearInterval(timerInterval);
            }

            swal.getContent().querySelector('#show_timeout').textContent = (Math.round(swal.getTimerLeft()/1000)*1000)/1000 + 's';

        }, 1000);
    },
    onClose: () => {
        clearInterval(timerInterval)
    },

    showConfirmButton: false,
});

我发现与计时器一起使用的唯一功能是Swal.getTimerLeft()。

我在https://codepen.io/teoui/pen/MzdzWy中创建了一支可与之玩耍的笔

谢谢!

1 个答案:

答案 0 :(得分:0)

我是SweetAlert2的作者,刚刚发布了具有Swal.stopTimer()支持的新版本。

这是使用方法:

Swal({
  title: 'Auto close alert!',
  html: 'I will close in 5 seconds. <a href id="stop-timer">Stop timer</a>',
  timer: 5000,
  onOpen: () => {
    Swal.getContent().querySelector('#stop-timer').addEventListener('click', e => {
      e.preventDefault()
      Swal.stopTimer()
    })
  }
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@7"></script>