我正在学习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.
如何获取check(num)函数的最后一个参数?
P.S。对不起我的英语我一直在努力描述尽可能好。
答案 0 :(得分: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);
}