A
A
Alexey Dzyuba2017-11-09 16:40:30
JavaScript
Alexey Dzyuba, 2017-11-09 16:40:30

Why does this function work (closures in javascript)?

There is a code:

The code
var div = document.querySelector('.test');

    function hide(elem, t) {
        var fadeEffect = setInterval(function () {
            if (!elem.style.opacity) {
                elem.style.opacity = 1;
            }

            if (elem.style.opacity < 0.02) {
                clearInterval(fadeEffect);
                elem.style.display = "none";
            }

            elem.style.opacity -= 0.02;
        }, t)
    }

    div.onclick = function () {
        hide(this, 19);
    }
Link to jsfiddle.
Gives a fadeOut effect like in jQuery. I tried stuffing the inside of the setInterval into a function. And to my surprise, I succeeded. But I don't understand why I can still insert my argument tinto the arguments of the function hide(). Thank God of course that works, but I would like to figure it out!
I just thought that I twould not be able to reach the time argument in setInterval.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Mashletov, 2017-11-09
@Alex_Dz

I don't understand anything. You pass the t parameter to hide. Inside hide, you use the t parameter as an argument to the setInterval function.
Because you declared that the function can have a parameter t and passed it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question