'How to run a function once a section is in view, using locomotive scroll?

I'm trying to run a function once a specific div is in view, and I only want it to run once. Does anyone know how to do this with locomotive scroll?

I tried the below code, but it runs every time I scroll. I want it to be true once and then stop checking if the div has the class 'in-view'.

//check object is in view
locoScroll.on('scroll', (args) => {

    if($('.curved_text_and_image').hasClass('is-inview')) {
        // Image Clone
        $(".curved_text_and_image__right-col").each(function() {
            let _this = $(this);
            var timesRun = 0;
            var interval = setInterval(function(){
                timesRun += 1;
                if(timesRun === 6){
                    clearInterval(interval);
                }
                    _this.find("img:first-child").clone().appendTo(_this);
                    _this.find('img').each(function(i){
                        var num = i + 1;
                        $(this).removeClass('img-1');
                        $(this).addClass('img-' + num );
                    });
            }, 100); 
        }); 

    }

});


Solution 1:[1]

First of all, I think is more clean to use the method data-scroll-call to trigger your function. Check the section 'Advanced' on the docs

Anyway, to solve your problem, just create a variable to check if you're code has already been executed. Decleare it at first and use it in your if statement like so:

let inviewTriggered = false;

locoScroll.on('scroll', (args) => {

    if($('.curved_text_and_image').hasClass('is-inview') && !inviewTriggered) {
        
        inviewTriggere = true;
        // Image Clone
        $(".curved_text_and_image__right-col").each(function() {
            let _this = $(this);
            var timesRun = 0;
            var interval = setInterval(function(){
                timesRun += 1;
                if(timesRun === 6){
                    clearInterval(interval);
                }
                    _this.find("img:first-child").clone().appendTo(_this);
                    _this.find('img').each(function(i){
                        var num = i + 1;
                        $(this).removeClass('img-1');
                        $(this).addClass('img-' + num );
                    });
            }, 100); 
        }); 

    }

});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MatteoIommi