Function bugs when clicking multiple times

I have created a fade in function but when i click it very quickly multiple times it start flickering
I dont know if there is a solution to that?
code:

html :

<button id="Fadetest" onclick="FadeTest()">fadetest </button>
            <div id="testblock">test</div>

css:

#testblock{
    width: 50px;
    height: 50px;
    background-color: red;
}
function FadeTest() {
    const getblock = document.getElementById("testblock");
    let opacatiy = 0.1;
    getblock.style.opacity = opacatiy;
    let fadefunc = setInterval(fade, 5);
    function fade() {
        if (opacatiy >= 1) {
            clearInterval(fadefunc);
        } else {
            opacatiy = opacatiy + 0.005;
            getblock.style.opacity = opacatiy;
        }
    }
}

I have used 5 miliseconds in the setinterval and a + 0.005 for the opacity
because i want it to fade-in smoothly.
But if there is a better way to achive that please let me know that as well.

The fading takes about 1 second to finish, and if you click repeatedly during that period, you have multiple intervals running. You can see that if you add console.log(fadefunc, opacatiy) to your fade function. For instance, interval 1 is almost finished and busy changing the opacity between 0.9 and 1, while interval 2 sets values between 0.2 and 0.3 at the same time.

But anyway, using CSS animations for this would be much more suited.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.