DEV Community

safejourney-art
safejourney-art

Posted on

Flashing light

Hello!
Is your beautiful imagination static or dynamic? If the answer is the latter, sure that you want animations: fadein, fadeout, flashing light and stuff. Actually they need a CSS style, which is called "opacity." However, in many cases, CSS is static (a choice to be dynamic is to use @keyframes). So, making dynamic is just a job of JavaScript.

The magic word is setTimeout but there is a tricky part. The code you want is as follows.

<div id="flash">FLASH</div>
<script>
  var i = 0;
  function flash(){
    if(i < 50){
      document.getElementById("flash").style.opacity = (-1)**i;
      i++;
      var sto = setTimeout(flash, 500);
    }else{
      clearTimeout(sto);
    }
 }
</script>

The tricky part is (-1)**i. This means -1 to the ith power. The i takes an integer which equals 0 or above, so either it takes -1 or 1. -1 is same as 0 for opacity, so this corresponds to just turning on and off the light!

How to use setTimeout() is setTimeout(function, time). It means that setTimeout performs the function after the time (milliseconds). In the example above, if the i is less than 50, setTimeout performs the flash after 500 milliseconds. If the i reaches 50, clearTimeout interrupts the job of setTimeout, namely flashing light stops.

I almost forgot. There is one more thing.
Don't forget to make an opportunity to start the flash function. For example, if you write <body onload="flash()"> in HTML, it just starts.
Well, safe journey!

Oldest comments (0)