Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda