0
var interval = window.setInterval(animate, 500);
var i = 5;
function animate() {
    if (i > 1) {
        i--;
        console.log(i);
    } else {
        window.clearInterval(interval);
    }
}
animate();

上面的 javascriptvar i = 5;和控制台记录了数字 5、4、3、2 和 1。DEMO fiddle

我想将起始数字animate()作为参数放入函数中,所以我添加了一个参数animate(),将变量 i 定义为单独var i;,并将一个数字放入animate()

var interval = window.setInterval(animate, 500);
var i;
function animate(i) {
    if (i > 1) {
        i--;
        console.log(i);
    } else {
        window.clearInterval(interval);
    }
}
animate(10);

演示小提琴

但是,第二次尝试只吐出数字 9,并没有吐出 10、9、8、7 等。

有谁知道我做错了什么?

4

4 回答 4

2

相反,您可以让该函数递归调用自身,并setTimeout与传入当前值的匿名函数一起使用i

function animate(i) {
    if (i > 1) {
        i -= 1;
        console.log(i);
        setTimeout(function() {
            animate(i);
        }, 500);
    }
}

animate(10);

这样就不需要管理区间,动画只会由animate()方法控制。更清洁的海事组织。

工作小提琴:http: //jsfiddle.net/UNkhK/

如果你仍然想控制超时:你也可以通过把他变成一个对象来扩展这个人的功能。

function Animation(delay) {
    this.delay = delay || 500;
    this.timeout = null;
}

Animation.prototype.animate = function(i) {
    if (i > 1) {
        i -= 1;
        console.log(i);
        var self = this;
        this.timeout = setTimeout(function() {
            self.animate(i);
        }, this.delay);
    }
}

Animation.prototype.stop = function() {
    clearTimeout(this.timeout);
}

var animation = new Animation(500);
animation.animate(10);

// Testing
setTimeout(function() {
    animation.stop();
    console.log('Animation stopped prematurely!');
}, 2000);

工作小提琴/演示:http: //jsfiddle.net/5dZyd/

于 2013-09-29T05:14:05.037 回答
1

你没有使用变量i,你创建了一个新变量,简而言之,i在函数定义中 -为函数animate(i)创建一个新var i变量,并且不使用全局变量

var i = 10;
function animate() {
    if (i > 1) {
    i--;
    console.log(i);
}
/*
    rest of your code here
*/
animate();

请参阅javascript 范围

也使用setTimeoutsetInterval 不到这里

小提琴

于 2013-09-29T05:11:25.527 回答
1

函数参数是影响全局变量的局部变量。因此,如果您i对参数使用相同的名称,则无法访问具有该名称的全局变量。您需要使用不同的变量。

var global_i;
function animate(local_i) {
    if (local_i !== undefined) { // Will be undefined when called from setInterval
        global_i = local_i;
    }
    if (global_i > 1) {
        global_i--;
        console.log(global_i);
    } else {
        window.clearInterval(interval);
    }
}
animate(10);
于 2013-09-29T05:13:26.203 回答
1

你可以试试这个(从函数本身调用函数并传递变量i

var interval;
function animate(i) {
   if (i > 1) {
        i--;
        console.log(i);
        interval = setTimeout(function(){ animate(i) }, 500);
    }
}
animate(10);

小提琴。

于 2013-09-29T05:18:20.097 回答