Mir Stephen
Mir Stephen

Reputation: 1927

How to run a function when scroll reaches a certain component?

There are some components stacked on top of each other and the last component has a timer. I want the timer to start only when that component is visible on screen or when scroll is reached to that component. [REPL]

let count_val = 80;
    
let count = 0;
function startTimer() {
    let count_interval = setInterval(() => {
        count += 1;

        if(count >= count_val) {
            clearInterval(count_interval);
        }
    }, 100);
}

// check if scroll reached to component and run below function.
startTimer();

How do I achieve this?

Upvotes: 0

Views: 448

Answers (1)

Corrl
Corrl

Reputation: 7699

Like commented this can be achieved using Intersection Observer and an action

REPL

<script>
    let count_val = 80;
    let count = 0;

    function timer(node) {
        let interval
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if(entry.isIntersecting) {                  
                    interval = setInterval(() => {
                        count += 1;
                        if(count === count_val) {
                            clearInterval(interval);
                        }
                    }, 100);
                } else {
                    clearInterval(interval)
                    count = 0 
                }
            })
        })
        observer.observe(node)

        return {
            destroy: () => observer.disconnect()
        }
    }
</script>

<div use:timer>
    <p>
        Counter - {count}
    </p>
</div>

<style>
    div {
        height: 100vh;
        display: grid;
        place-items: center;
        background-color: teal;
        color: #0a0a0a;
        font-size: 4rem;
    }
</style>

Upvotes: 3

Related Questions