【发布时间】:2020-04-07 18:08:23
【问题描述】:
谁能告诉我为什么我不能暂停循环?这个想法是暂停它 5 秒钟,然后重新启动它。代码如下。谢谢!
let pics = [{
name: 'picture',
picture: 'https://images.unsplash.com/photo-1491555103944-7c647fd857e6?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80',
number: 1
},
{
name: 'picture',
picture: 'https://images.unsplash.com/photo-1495837174058-628aafc7d610?ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80',
number: 2
},
{
name: 'picture',
picture: 'https://images.unsplash.com/photo-1474314881477-04c4aac40a0e?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80',
number: 3
}
];
let pauseLoop = false;
function displayImage() {
let display = document.querySelector('#display');
let button = document.querySelectorAll('.pic');
for (let i = 0; i < button.length; i++) {
button[i].addEventListener('click', function() {
display.style.backgroundImage = "url('" + pics[i].picture + "')";
// THIS IS SUPPOSED TO PAUSE THE LOOP FOR 5 SECONDS AND THEN RESTART THE LOOP
pauseLoop = true;
setTimeout(function() {
pauseLoop = false;
console.log(pauseLoop)
}, 5000);
})
}
}
// create list inside nav
let createGalleryMeny = () => {
let nav = document.querySelector('#nav');
for (let i = 0; i < pics.length; i++) {
let img = document.createElement('DIV');
img.style.backgroundImage = "url('" + pics[i].picture + "')";
img.className = 'pic';
nav.appendChild(img)
}
}
// loop through every picture
function loopPics() {
let number = 0;
let display = document.querySelector('#display');
display.style.backgroundImage = "url('" + pics[pics.length - 1].picture + "')";
if (pauseLoop !== true) {
setInterval(function() {
display.style.backgroundImage = "url('" + pics[number].picture + "')";
number++
if (number === pics.length) {
number = 0
}
}, 2000)
}
}
(() => {
createGalleryMeny();
loopPics();
displayImage()
})();
此代码只是一个简单的图库,我希望可以选择在单击图库中的任何图片时暂停循环,显示单击的图片并在 5 秒后重新启动循环。
【问题讨论】:
-
谁能告诉我为什么我不能暂停循环?因为循环不能暂停?
setTimeout()是一个异步操作,与循环同时工作。回调函数仅在 a) 指定的时间量已经过去 b) JavaScript 运行时空闲时运行,这意味着当前函数(及其循环)已完成。 -
@ScottMarcus 看我的帖子,有可能,但这可能不是最好的解决方案
-
@Niels 好吧,可以编写产生延迟的代码,但从技术上讲,您不能暂停循环。
标签: javascript loops settimeout pause