У меня есть функция, заданная в переменной, которая вызывается несколько раз и должна зацикливаться после первого раза.
После выполнения моего кода я думаю, что это куда-то, но я не могу найти его
Вот мой код:
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/
setTimeout
не признает в качестве третьего параметра имя функции.
Взгляните на это. Вы не можете циклы волшебным образом с помощью setTimeout :)
Я бы порекомендовал вам использовать setInterval
вместо или использовать функции закрытия и правильный for
цикла.
Поскольку вы уже используете jQuery, я создал пример без явного использования setTimeout
или setInterval
вообще - просто из любопытства :)
Вся магия выполняется с помощью $.when
и отложенных объектов
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();
Обновить
Код для требования из комментариев
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