Odinn
Odinn

Reputation: 1106

How to get the value for one function to another?

I'm learning Javascript, I read about scope and variables but can't get information about how to send variables between the functions. Please can someone to explain how to be with this situation and it would be great to recommend something to read about it.

I want to draw a picture 30 times with 30 different parameters, and get the last parameter for checking function:

function loadImg{  
 .....
      img.onload = function() {   // Loading first picture at the start
        ........
           boo.onclick = function() {  // the function which by click start all process
               var i = 0;
               var num;  // the variable which I'm going to use for random numbers.
           setInterval(function() {      
               //   here I'm generating random numbers
                num = Math.floor(Math.random() * imgs.length);
            // and then start draw() function, which is going to get the 'num' parameter and draw a pictures with time interval ONLY 30 times
              if(i < 30){                    
              draw(num);
              i++; }, 2000);

            check(num); // after all, I want to run "check()" function which is going to get THE LAST from that 30 generated 'num' parameter and check some information. But is undefined, because it's outside the setInterval function and I don't wont to put it in, because it will starts again and again.

How to get the last parameter for check(num) function?

P.S. Sorry for my english I've been trying to describe as good a as I can.

Upvotes: 2

Views: 53

Answers (1)

Curtis
Curtis

Reputation: 103348

You could call check(num) inside the setInterval() function with a condition:

if(i < 30){                    
  draw(num);
  i++;
}
else
{
   check(num);
}

You should also then end your loop as this will keep running indefinitely.

To do this assign the interval to a variable:

var myInterval = setInterval(function() { 

And then clear the interval before calling check():

if(i < 30){                    
  draw(num);
  i++;
}
else
{
   clearInterval(myInterval);
   check(num);
}

Upvotes: 2

Related Questions