JavaScript shutdown problem, please explain

This is a feature taken from the Pro JavaScript methods that I am trying to understand, but not. The purpose of the function is to slowly reveal the hidden element by increasing its height within one second. Comments in the code are provided by the author of the book. I don’t understand anything, starting from where the author says in the comment “closing to make sure that we have the right to“ me ”.

Could you explain as much as possible.

a) how this closure works in this function. That is how he will make sure that he has the right "i" and that in the code does this important.

b) why is there a comma near the end of the program after elem in the code elem,.style.height

c) what is the purpose of this piece of code (pos + 1) * 10). How does this work with the setTimeout function?

function slideDown(elem) {
  //start the slide down at 0
  elem.style.height = '0px';

    //Show the element, but can`t see it because height is 0
   show(elem);

    //find the full potential height of the element
    var h = fullHeight(elem);

   //We`re going to do a 20 frame animation that takes place over one second
   for (var i = 0; i <= 100; i +=5 ) {
         //a closure to make sure that we have the right 'i'
         (function() {
           var pos = i;

          //set the timeout to occur at the specified time in the future
          setTimeout(function() {

            //set the new height of the element
             elem,.style.height = (pos/100) * h) + "px";

         }, ( pos + 1) * 10);
       })();
     }
}
+3
4

a) - setTimeout(). setTimeout() , , i , setTimeout(). "" i pos i , . pos (, i).

b) , . : , . .

c) , setTimeout , i. ; setTimeout(..., 10), 10 , , . pos "" setTimeout. , , setTimeout() 20 ( 20FPS).

+3

, i, .. . .

   (function(index) {
       var pos = index;

      //set the timeout to occur at the specified time in the future
      setTimeout(function() {

        //set the new height of the element
         elem.style.height = ((pos/100) * h) + "px";

     }, (pos + 1) * 10);
   })(i);

i , , index .

javascript.

+1

a), i, , , , i i . , ( ), . , , .

, i, N pos ( N ), , setTimeout, .

b) .

c) This is the time in milliseconds of delay. In the algorithm, it seems that it will crop the size of the first element by 10 milliseconds, the second by 20, etc.

These functions work as follows:, setTimeout(callback, milliseconds)and the function can be anonymous, therefore it setTimeout(function() { ... }, 10)is a valid syntax.

Good luck

+1
source

c) this code launches a series of setTimeout calls that create an animation. The code (pos + 1) * 10 ensures that each setTimeout happens a little later than the previous one, thereby stunning every call that causes the animation.

+1
source

All Articles