Home > Blockchain >  jQuery setInterval by 5 seconds and Increment by previous interval
jQuery setInterval by 5 seconds and Increment by previous interval

Time:05-15

I am displaying the jQuery modal after 5 seconds using setInterval. I want to increment the number of seconds by the previous interval value.

Let's say the page loads and the modal appears after 5 seconds, next time modal should appear after 10 seconds (incremented interval by previous value 5 5), then 20 seconds, then 40 seconds, and so on...

I have the following Code, But only firing every 5 fixed seconds:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<!-- jQuery Modal -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
<script>
  $(document).ready(function() {
    setInterval(function() {
      $('#ex1').modal();
    }, 5000);
  });
</script>
<style>
  .modal {
    max-width: 70% !important;
  }
</style>
<!-- Modal HTML embedded directly into document -->
<div id="ex1" >
  <a href="https://example.com">
    <img alt="image" src="https://example.com/image.png" />
  </a>
</div>

How can I implement the above condition?

CodePudding user response:

I think setInterval() is not the right tool. I'd go with setTimeout(), with an event that fires when the modal is closed and a global counter that doubles its value each time you close the previous modal.

let counter = 5000;

function repeatTimeout(ms) {
  console.log('counter is: '   ms);
  return setTimeout(function() {
    $('#ex1').modal();
    counter *= 2;
  }, ms);
}

$(document).ready(function() {
  let timer = repeatTimeout(counter);

  $('#ex1').on($.modal.AFTER_CLOSE, function() {
    console.clear();
    console.log('closed modal');
    clearTimeout(timer);
    timer = repeatTimeout(counter);
  })
});
.modal {
  max-width: 70% !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<!-- jQuery Modal -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />


<div id="ex1" >
  <a href="https://example.com">
    <img alt="image" src="https://example.com/image.png" />
  </a>
</div>

  • Related