Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda