javascriptjquerybootstrap-modal

show a modal pop up for 10 seconds or until a flag or variable is set


I am a beginner in jquery so pardon for the mistakes. I want to show a modal pop up for 10 seconds or until a flag or variable is set, then hide this modal pop up and then open another one depending on the flag or variable. Here is the code that I have done so far,

$(document).ready(function() {
$("#btnopen").click(function() {
    $('#myModal1').modal('show');

    setTimeout($('#myModal1').modal('hide'), 10000);  //show myModal1 for 10 seconds
  if({{ flag }}){
    $('#myModal1').modal('hide');
   $('#myModal2').modal('show');  //If flag is set close myModal1 and open myModal2
}
else{
      $('#myModal1').modal('hide');
    $('#myModal3').modal('show');  //else close myModal1 and open myModal3
}
});
$("#btnClose1").click(function() {
  $('#myModal1').modal('hide');
});
$("#btnClose2").click(function() {
  $('#myModal2').modal('hide');
});
$("#btnClose3").click(function() {
  $('#myModal3').modal('hide');
});});

The issue now I am facing is I cannot show myModal1 for 10 seconds. I have searched some documents but nothing solved my problem. Can anyone help me?.
Edit
What should I do if I want the myModal1 pop up close only after the flag is set else, after 30 seconds close myModal1 pop up and open myModal3 pop up. Thanks in advance.


Solution

  • Try the code, this may help you

    var myVar;
        $(document).ready(function () {
          $("#btnopen").click(function () {
            $('#myModal1').modal('show');
    
            myVar=setTimeout(function(){
        $('#myModal1').modal('hide');
    
        if (flag){
            $('#myModal1').modal('hide');
            $('#myModal2').modal('show');  //If flag is set close myModal1 and open myModal2
          }
        else{
            $('#myModal1').modal('hide');
            $('#myModal3').modal('show');  //else close myModal1 and open myModal3
          }
            }, 10000);  //show myModal1 for 10 seconds
    
        });
    
    
        $("#btnClose1").click(function () {
          $('#myModal1').modal('hide');
    clearTimeout(myVar);
        });
        $("#btnClose2").click(function () {
          $('#myModal2').modal('hide');
    clearTimeout(myVar);
        });
        $("#btnClose3").click(function () {
          $('#myModal3').modal('hide');
    clearTimeout(myVar);
        });
    
        });
    

    Do not put the following code just after setTimeout(function(){},10000); because the following code will get execute just after setTimeout(function(){},10000); and will not wait for 10 sec. this is an async execution will callback after 10 sec

    if({{ flag }}){
        $('#myModal1').modal('hide');
       $('#myModal2').modal('show');  //If flag is set close myModal1 and open myModal2
    }