OIM3690 - Web Technologies

contain

Animation using JavaScript

setTimeout()

  • setTimeout() is a built-in function in JavaScript that allows you to schedule the execution of a function or a block of code after a set amount of time.
    • It is useful when you need to delay the execution of a piece of code, such as an animation or a network request, to avoid blocking the main thread.
    • It will execute once after the specified time has passed (in milliseconds).
  • Syntax:
    setTimeout(function, delay);
    

setTimeout() Example

  • Example:
    setTimeout(function () {
        console.log("See me in 1 second!");
        }, 1000);
    
  • This example schedules the execution of an anonymous function that logs a message to the console after a delay of 1000 milliseconds (i.e., 1 second).
  • Note: setInterval() is another built-in function that is similar to setTimeout().
    • However, setInterval() executes the specified function repeatedly at a set interval until stopped or cleared.
    • This can be useful when you need to repeatedly execute a task, such as polling a server for updates.

setTimeout() vs. setInterval()

Function Executes Once? Repeats? How to Cancel? Typical Use Case
setTimeout() ✅ Yes ❌ No clearTimeout() Delays, animations, user feedback
setInterval() ❌ No ✅ Yes clearInterval() Polling, repeated tasks, timers

setTimeout() in Recursion

  • Example:
    function animate() {
      // Example: update position of an element
      console.log("Animating...");
      ... // Animation code here
      setTimeout(animate, 1000); // Calls itself again after 1 second
    }
    
    • This creates a recurring animation with a delay of 1000 milliseconds between each cycle.
  • Recursion is useful, but be careful: without a stop condition, it can cause infinite loops.

Global Variables vs. Local Variables

  • Global variable
    • Declared outside any function
    • Accessible anywhere in the script
    • Keeps its value between function calls
  • Local variable
    • Declared inside a function
    • Only accessible within that function
    • Created on each call, destroyed when the function ends

Examples

  • Example 1 (local variable counter):
    function doThis() {
      let counter = 0;
      counter++;
    }
    
    • Every time doThis() runs, counter is reset to 0 and then incremented to 1.
  • Example 2 (global variable counter):
    let counter = 0;
    function doThat() {
      counter++;
    }
    
    • counter keeps increasing every time doThat() is called.

Exercise: Creating a Slide-show (ex21.html)

  • Create a new HTML file, ex21.html.
  • Declare a global variable slides as an array of image sources:
    const slides = [
      "images/tiger1.jpg", 
      "images/tiger2.jpg",
      ];
    
  • Add an <img> tag to your HTML code as a placeholder for the changing image.
  • Use DOMContentLoaded to start the slideshow automatically
  • Write a function, changeSlide():
    • Update image
    • Cycle through the slides array
    • Call itself again after 1000ms using setTimeout()

ex21.html

const slides = [
  "images/tiger1.jpg",
  "images/tiger2.jpg",
  // more
];
let currentSlideIndex = 0;

function changeSlide() {
  const img = document.getElementById("tiger");
  if (currentSlideIndex === slides.length) {
    currentSlideIndex = 0;
  }
  img.src = slides[currentSlideIndex];
  currentSlideIndex++;
  setTimeout(changeSlide, 1000);
}

document.addEventListener("DOMContentLoaded", changeSlide);

Exercise: ex21.html (Challenge)

  • Can you add border that changes color with each image?
  • Can you add a text caption that describes each slide?
  • Can you add a button that starts/stops the slideshow again?
  • Hint: Use a second array for captions, or assign custom data attributes to each image.

Another Animation using JavaScript - Moving Lyrics

  • Download lec21-js-moving-lyrics.html from OIM3690/resources/templates
  • Read code, including
    • JavaScript
    • CSS (important in this example)
  • Answer the following questions:
    • What are the global variables?
    • What is the purpose of each variable?
    • Can you make the movement faster? More smoothly?

Questions?

Use global variables sparingly, as they can make it difficult to track changes to the value of the variable throughout the code. Use local variables whenever possible, as they are more efficient and reduce the risk of unintended changes to the value of the variable. Note: It is possible for a local variable to have the same name as a global variable, but the local variable will only be accessible within the function where it is defined.