Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
Using intersection observer to start and stop JavaScript animation

I am working on a JavaScript typing animation, however I don't want to take the performance hit while the animation is not on the screen, hence I want it to only animate when it's on screen by using Intersection Observer.

I can successfully start the animation using Intersection Observer but I'm having trouble figuring out how to pause it when it's off screen.

Here is my code:

let typingobserver = new IntersectionObserver((elements) => {
    elements.forEach(element => {
        if (element.isIntersecting) {
            console.log ("on screen!!");
            typequeries('.target');
        } else {
            console.log ("not on screen!!");
        }   
    });
});

let typingobserverelements = document.querySelector('.target');
typingobserver.observe(typingobserverelements);


async function typequeries(element) {
    element = document.querySelector(element);
    queries = JSON.parse(element.getAttribute('data-queries'));
    let i = 0;
    while(true) {
        await type(queries[i], element);
        await wait(2000);
        await (element.innerHTML = "");
        i++;
        if(i >= queries.length) {i = 0;}
    }
}

async function type(query, element) {
    const characters = query.split("");
    let i = 0;
    while (i < characters.length) {
        await wait(Math.floor(Math.random() * 150) + 50);
        element.append(characters[i]);
        i++
    }
    return;
}

function wait(ms) {
    console.log (ms);
    return new Promise(resolve => setTimeout(resolve, ms));
}
<span class="target" data-queries='["typed text", "is fun", "to read"]'></span>

How can I both start the animation when it's observed with Intersection Observer and then pause it when it's off screen?

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!