skip to Main Content

I tried to make an animation on javascript.

It should look like:

Frame 1:

ඞ______ _

Frame 2:

_ඞ_____ _

Frame 3:

__ඞ____ _

Frame 4:

___ඞ___ _

I want to something that changes the text after some seconds. So I’ve got a label and this is a snippet of a code.

document.getElementById('label').innerHTML='ඞ______ _';

sleep(500);

But if I use the sleep function, the page ‘waits’ until my ‘animation’ is finished and then I can see the last text:

___ඞ___ _

Is there a way to solve this problem?

2

Answers


  1. You should use a async function for updating the animation at the same time of doing the other stuff your javascript is doing.

    an async function looks like this

    async renderAnimation () {
        setTimeout(() => {this.animate() }, 500);  
    }
    
    animate(){
        document.getElementById('label').innerHTML='ඞ______ _';
    }
    
    

    You should check this link for a more in deep explanation of async: https://www.w3schools.com/js/js_async.asp

    Login or Signup to reply.
  2. You need to code your thing to use an interval or timeout.

    function annimateText(elem, frames, ms) {
    
      let index = 0;
      let timer;
      
      const stop = () => window.clearTimeout(timer);
      
      const update = () => {
        elem.textContent = frames[index];
        index++;
        if (frames.length <= index) stop();
      };
    
      timer = window.setInterval(update, ms);
      
      update();
    
      return {
        stop: timer,
      };
    }
    
    
    const frames = [
      "ඞ______ _",
      "_ඞ_____ _",
      "__ඞ____ _",
      "___ඞ___ _",
      "____ඞ__ _",
      "_____ඞ_ _",
      "______ඞ _",
      "_______ඞ_",
    ]
    annimateText(document.querySelector("#out"), frames, 100);
    #out {
      font-family: monospace;
    }
    <span id="out"></span>

    Now can you do sleeps? Yes you can do it with async and await.

    async function outputAndWait (text) {
      document.querySelector("#out").textContent = text;
      await sleep(100);
    }
    
    async function sleep (ms) {
      return new Promise((resolve) => {
        window.setTimeout(resolve, ms);
      });
    }
    
    async function animateIt () {
      await outputAndWait("ඞ______ _");
      await outputAndWait("_ඞ_____ _");
      await outputAndWait("__ඞ____ _");
      await outputAndWait("___ඞ___ _");
      await outputAndWait("____ඞ__ _");
      await outputAndWait("_____ඞ_ _");
      await outputAndWait("______ඞ _");
      await outputAndWait("_______ඞ_");
    }
    
    animateIt();
    #out {
      font-family: monospace;
    }
    <span id="out"></span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search