DEV Community

safejourney-art
safejourney-art

Posted on

2

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!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay