Core JavaScript

Animation - Flashing Dot

We can create a simple animation using a timed loop that is generated by recursive calls to the setTimeout(). The setTimeout() function is called with a function and a time passed in as parameters. The function that is passed in is the function that setTimeout() will call after the time interval has expired.

In the example code below, we pass in AnimationLoop and 500 so that the function AnimationLoop() is called after 500 milliseconds. Since AnimationLoop() calls setTimeout() at the end of its execution, it sets up a loop that is executed every 500 milliseconds. This loop creates a timed animation.

The if statement inside the function toggles the display of the "dot" to create the flashing dot effect. Setting the display style property value to none means that the element, in this case a div, is not shown. The value block makes the div display as normal.

The two div elements, the gray background and the black dot, are created and styled in the Initialize() function, which is called in the beginning to trigger the animation loop.

Once these two files are created and saved in the same folder, we can double-click the file "FlashingDot.html" to begin the animation, as shown below.

FlashingDot.html

<!DOCTYPE html>
<html>
<head>
  <title>XoaX.net's Javascript Flashing Dot Animation</title>
</head>
<body>
  <script type="text/javascript" src="FlashingDot.js"></script>
</body>
</html>

FlashingDot.js

var qpBkdg = null;
var qpDot = null;
var qpBody = null;

function AnimationLoop() {
  if (qpDot.style.display == 'block') {
    qpDot.style.display = 'none';
  } else {
    qpDot.style.display = 'block';
  }
  setTimeout(AnimationLoop, 500);
}

function Initialize() {
  qpBody = document.getElementsByTagName("body")[0];

  qpBkdg = document.createElement('div');
  qpBody.appendChild(qpBkdg);
  qpBkdg.style.width = '400px';
  qpBkdg.style.height = '300px';
  qpBkdg.style.background = '#aaaaaa';
  qpBkdg.style.position = 'absolute';
  qpBkdg.style.left = '25px';
  qpBkdg.style.top = '35px';

  qpDot = document.createElement('div');
  qpBkdg.appendChild(qpDot);
  qpDot.style.width = '20px';
  qpDot.style.height = '20px';
  qpDot.style.background = '#000000';
  qpDot.style.position = 'absolute';
  qpDot.style.left = '190px';
  qpDot.style.top = '140px';

  AnimationLoop();
}

window.onload = Initialize;
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.