2015-06-08 45 views
2

我正在学习Javascript,我读了关于范围和变量的信息,但无法获得有关如何在函数之间发送变量的信息。 请有人可以解释如何与这种情况,这将是很好的推荐的东西来阅读它。如何获取一个函数的值到另一个?

我想画一幅画30次与30个不同的参数,并得到检查功能的最后一个参数:

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. 

如何获得检查(NUM)函数的最后一个参数?

P.S.对不起,我的英语我一直试图尽可能好地描述。

+1

,应清除的时间间隔时,即可大功告成。 –

+0

谢谢!它帮助,我用如果其他{clearInterval并运行我的check()函数} – DarthJS

回答

2

你可以称之为check(num)setInterval()函数内部有一个条件:

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

你也应该然后结束循环,因为这会无限期地运行。

要做到这一点的时间间隔分配给一个变量:

var myInterval = setInterval(function() { 

,然后调用check()之前清除区间:

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

我想它不会帮助,如果“setInterval”内,“检查”()函数将运行多次 – DarthJS

+0

@DarthJS请参阅我的更新,我忘了提及你应该清除间隔,一旦它不再使用。这也会阻止'check()'多次运行。 – Curt

+0

非常感谢!这真的是我需要! – DarthJS

相关问题