超时循环不起作用

时间:2013-09-26 10:47:55

标签: jquery css settimeout

我在一个被调用多次的变量中设置了一个函数,并且应该在它第一次通过之后循环。

在我的代码发现后,我认为这是一个滑动的地方,但我找不到它

这是我的代码

setTimeout(function () {
    var tre_heartbeat_small;
    playing = function () {
        tre_heartbeat_small = function () {
            //stuff it does
        }
    }

    function heartbeatloop() {
        function () {
            playing();
        }
        setTimeout(function () {
            playing();
        }, 800, heartbeatloop)
    }
    heartbeatloop();
}, 1500);

这里有一个小提琴http://jsfiddle.net/nRwkz/

2 个答案:

答案 0 :(得分:1)

setTimeout不承认函数名称为第3个参数。

看看this。 你不能用setTimeout神奇地循环:)

我建议您改用setInterval或使用闭包函数和正确的for循环。

答案 1 :(得分:1)

由于您已经在使用jQuery,我已经设置了一个示例,但没有明确使用setTimeoutsetInterval - 只是出于好奇:) 所有魔法都是通过$.whendeferred objects

完成的
var timer = 500,
    animateLow = function (callback) {
        $.when($("#test").animate({
            height: '977px',
            width: '1080px',
            left: '49.5%',
            top: '370px'
        }, timer)).done(callback);
    },
    animateHigh = function (callback) {
        $.when($("#test").animate({
            height: '944px',
            width: '1044px',
            left: '50%',
            top: '380px'
        }, timer)).done(callback);
    };

function heartbeatloop() {
    animateLow(function () {
        animateHigh(heartbeatloop);
    });
}

heartbeatloop();

fiddle

<强>更新
来自评论的要求代码

var element = $("#test"),
    animate_timer = 1000, // duration of the animation
    beat = [{
        // method for animation
        method: function() {
            element.text("low");
            return element.animate({height:'977px',width:'1080px',left:'49.5%',top:'370px'},animate_timer);
        },
        // time after which the next animation should start
        timeout: 0
    }, {
        method: function() {
            element.text("normal");
            return element.animate({height:'944px',width:'1044px',left:'50%',top:'380px'},animate_timer);
        },
        timeout: 1000
    }, {
        method: function() {
            element.text("high");
            return element.animate({height:'995px',width:'1100px',left:'49.3%',top:'360px'},animate_timer);
        },
        timeout: 3000
    }
];

function beatIt(idx) {
    idx = idx || 0;

    $.when(beat[idx].method())     // start the animation
     .done(function() {            // when finished start the next step in <timeout> milliseconds
        setTimeout(function() {
            beatIt((idx + 1) % beat.length);    // next step with reset after last element
        }, beat[idx].timeout);
    });
}

beatIt();    // start the beating
相关问题