Search code examples
jquerycountdown

Very simple second countdown with jQuery


I am trying to create a very simple count down just for the second. The message pop up, say something like "You will be redirected in 'X' seconds." That 'X' depends on what our end-user put in. Not sure why my code is not working.

if($('.ty').find('.form-ty-redirect').length !== 0){
  // alert("redirect here");

  $('.form-ty-redirect').each(function(){

    setInterval(function() {
    var count = $(this).find('#counter').html();
    $(this).find('#counter').html(count - 1);
  }, 1000);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="ty">
   <h4>Example# 1</h4>

   <p class="form-ty-redirect">You will be redirected in  <span id="counter">10</span> seconds.</p>
 </div>
 
 <div class="ty">
   <h4>Example# 2</h4>
   <p class="form-ty-redirect">You will be redirected in  <span id="counter">20</span> seconds.</p>
 </div>


Solution

  • this can be tricky to deal with as it is entirely dependent on scope. Inside your interval callback function it no longer references the same scope as the function it was declared in.

    Rather than using $(this) inside your interval callback, bind it as an argument for an anonymous function, like so.

    if ($('.ty').find('.form-ty-redirect').length !== 0) {
      //alert("redirect here");
    
      $('.form-ty-redirect').each(function() {
    
        (function(elm){
          setInterval(function() {
            var count = elm.find('#counter').html();
            elm.find('#counter').html(count - 1);
          }, 1000);
        })($(this));
    
      });
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="ty">
      <h4>Example# 1</h4>
    
      <p class="form-ty-redirect">You will be redirected in <span id="counter">10</span> seconds.</p>
    
    </div>
    
    <div class="ty">
      <h4>Example# 2</h4>
      <p class="form-ty-redirect">You will be redirected in <span id="counter">20</span> seconds.</p>
    
    </div>