Search code examples
javascripthtmljquerytimercountdown

I want the model popup to be closed based on current system time using jquery?


I want the model popup to be closed based on current system time. Right now, the model popup is not closing according to the current system time, in other words, the popup is closing on query static time. How do i close modal popup after 15 mintues from current system time?

Html Modal Popup

 <a href="javascript:void(0);" data-toggle="modal" data-target="#myModal" 
 class="btn btn-own btn-user redeem_btn"> Redeem Now </a>   

 <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" 
aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p id="countdown"></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Jquery

    $(document).ready(function() {
    $(".redeem_btn").on("touchstart, click", function(e) {

        var dt = new Date();
        var time =  dt.getMinutes();

        alert(time);

        $('#myModal').modal('show');
        //var counter = 15;
        var interval = setInterval(function() {
            //counter--;
            $("#countdown").html('Window will close in ' + counter + ' seconds.');

            if (time == 15) {

                $('#myModal').modal('hide');
                alert(time);
                clearInterval(interval);
            }
        }, time);
        $('body').bind('mousedown keydown', function(event) {
            //counter = 15;
        });
    });

});

Solution

  • JQUERY

    $(document).ready(function() {
      $(".redeem_btn").on("touchstart, click", function(e) {
    
        $('#myModal').modal('show');
    
        let time = 15 * 60 * 1000 // 15 minutes
        setTimeout(function(){ 
          $('#myModal').modal('hide');
          alert(time);
          clearInterval(interval);
        }, time);
    
        let interval = setInterval(function() {
          let minutes = Math.floor(time / 60000);
          let seconds = ((time% 60000) / 1000).toFixed(0);
          $("#countdown").html('Window will close in ' + minutes + ':' + seconds);
          time = time - 1000
          // comment `setTimeout` if use `if` 
          // if (time < 0) {
          //  alert(time);
          //  clearInterval(interval);
          // }
        }, 1000); // every 1 second
      });
    });