简体   繁体   中英

Call JS function only once for window scroll

I have a function that writes text (typewriter effect) when user scrolls to specific section. But I want to do it only once. So if user scrolls first time the text is written and that should be all. But If user scrolls again (doesn't matter in which direction) the function is called again so the text is being typed again and again... Here's the JS code:

var counter = 0;
$(window).on('scroll', (function () {
    counter ++;
    if(counter < 80){
        if ($(window).scrollTop() >= $('#anchor-form').offset().top - 200) {
            $(window).scrollTop();
            $('.form__icon').addClass('form--animate');
            showText("Some Text to be written", 0);
        }
    }
}));

function showText(msg, x) {
    if (x < msg.length) {
        $txt_form.html(msg.substring(0, x+1));
        x++;
        setTimeout(function() {
            showText(msg,x)
        }, 50)
    }
};

As You can see I've prevented it by setting counter. I've checked how many 'counts' would it be when window is scrolled to this section and just set the value inside the IF statement. But I feel that this is not sufficient and 'good practice' method. Sometimes the text is glitchy besides this prevention method. I've tried with jQuery .one() method also but it doesn't work.

I'll appreciate any suggestions.

在if语句中获取第二个计数器,并将其设置为counter2 ++,然后在if语句中检查count2 === 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM