Álvaro González
Álvaro González

Reputation: 146450

Performance-friendly blinking effect

I'd love to add a blinking effect like this, but I think setInterval is overkill for what's mere cosmetic stuff:

jQuery(function(){
  $("#watch").each(function(){
    var $box = $(this);
    var show = true;
    setInterval(function(){
      var m = moment();
      $box.text(show ? m.format('H:mm') : m.format('H mm'));
      show = !show;
    }, 500);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src='//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js'></script>
<div id="watch">--:--</div>

Is there a newer JavaScript API I could be using, or maybe a CSS transition?

Upvotes: 1

Views: 450

Answers (2)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146450

For the records, this is the final CSS I wrote based on George's answer:

section {
  font-size: 5rem;
}

.stop-watch span {
   animation: blink 1s infinite;
}

@keyframes blink{
  0% {
    animation-timing-function: steps(1, end);
    opacity: 1;
  }
  50% {
    animation-timing-function: steps(1, end);
    opacity: 0;
  }
}
<section class="stop-watch">
1<span>:</span>59
</section>

Upvotes: 1

George
George

Reputation: 6739

Using the CSS provided by this answer, you can do this

jQuery(function() {
  $("#watch").each(function() {
    var $box = $(this);
    setInterval(function() {
      var m = moment();
      $box.html(m.format('H') + '<span class="blink_me">:</span>' + m.format('mm'));
    }, 1000);

  });
});
.blink_me {
  animation: blinker 1s infinite;
}

@keyframes blinker {
  50% {
    opacity: 0;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src='//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js'></script>
<div id="watch">--:--</div>

Upvotes: 1

Related Questions