我有一个脚本应该每隔8秒调用另一个javascript函数。但是,在某些情况下,我需要跳过处理8秒延迟的seTimeout函数(它是一个滑块,根据用户点击的内容,我需要立即到达特定的幻灯片)。这可能在JavaScript中?
例如,根据用户点击的内容,我可能希望立即执行switchBullets(4); switchNews("Title 4", "image4.jpg", "image4Logo.jpg", "")
,无论动画目前在哪里。
脚本如下所示:
function animateNews() {
$(window).load(function() {
switchBullets(1);
switchNews("Title 1", "image1.jpg", "image1Logo.jpg", "");
setTimeout(function() { switchBullets(2); switchNews("Title 2", "image2.jpg", "image2Logo.jpg", "")
setTimeout(function() { switchBullets(3); switchNews("Title 3", "image3.jpg", "image3Logo.jpg", "")
setTimeout(function() { switchBullets(4); switchNews("Title 4", "image4.jpg", "image4Logo.jpg", "")
setTimeout(function() { animateNews();
}, 8000);
}, 8000);
}, 8000);
}, 8000);
}
)};
答案 0 :(得分:1)
将您的数据与逻辑分开。请改用setInterval()
使其永久运行。当用户点击时,请调用click()
并取消setInterval。
var timerId;
var data = [
{title: 'Title 2', img1: 'image2', img2: 'image2Logo.jpg', other: ''},
{title: 'Title 3', img1: 'image3', img2: 'image3Logo.jpg', other: ''},
{title: 'Title 4', img1: 'image4', img2: 'image4Logo.jpg', other: ''}
];
$(window).load(function() {
switchBullets(2);
switchNews("Title 2", "image2.jpg", "image2Logo.jpg", "");
timerId = beginSlider();
});
function beginSlider() {
var i = 1;
return setInterval(function () {
switchBullets(i+2);
switchNews(data[i].title, data[i].img1, data[i].img2, data[i].other);
if (i === 2) { i = 0; }
else { i += 1; }
}, 8000);
}
function click(j) {
clearInterval(timerId);
switchBullets(j+2);
switchNews(data[j].title, data[j].img1, data[j].img2, data[j].other);
// could start slider again after 8 sec.
// timerId = beginSlider();
}