Search code examples
javascriptjqueryprepend

jQuery function not working properly


I have a function which I copy from internet. It is working properly on load but when I add elements using prepend() spans on which function was already working start to blink I have add this to jsfiddle Please have a look any help will be appreciated.

$('.b').click(function(){
     $('.top').prepend('<div class="inner">brown fox jumps <span class="sinc"> 1462883724000 </span> </div>');
     $('.sinc').UpdateSince(1000);

});

Working snippet:

$.fn.UpdateSince = function(interval) {

  var times = this.map(function() {
    return {
      e: $(this),
      t: parseInt($(this).html())
    };
  });

  var format = function(t) {
    if (t > 86400) {
      return Math.floor(t / 86400) + ' days ago';
    } else if (t > 3600) {
      return Math.floor(t / 3600) + ' hours ago';
    } else if (t > 60) {
      return Math.floor(t / 60) + ' minutes ago';
    } else {
      return t + ' seconds ago';
    }
  }

  var update = function() {
    var now = new Date().getTime();
    $.each(times, function(i, o) {
      o.e.html(format(Math.round((now - o.t) / 1000)));
    });
  };

  window.setInterval(update, interval);
  update();

  return this;
}
$('.sinc').UpdateSince(1000);

$('.b').click(function() {
  $('.top').prepend('<div class="inner">brown fox jumps <span class="sinc"> 1462883724000 </span> </div>');
  $('.sinc').UpdateSince(1000);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="top">
  <div class="inner">
    brown fox jumps
    <span class="sinc">1462883724000</span>
  </div>
</div>

<input type="button" class="b" value="click me">


Solution

  • The problem is you're starting a new interval every time you click the button. You can either clear the previous interval before starting a new one or start the interval once and update the list.

    Here's an example of clearing the interval:

    var updateInterval; // Store the interval ID here
    
    $.fn.UpdateSince = function(interval) {
    
      ...
    
      // Clear the previous interval
      clearInterval(updateInterval);
      updateInterval = setInterval(update, interval);
      update();
    
      return this;
    };