Can anyone tell me why I'm not being able to pause the loop? The idea is to pause it for 5 seconds and then restart it. The code is bellow. Thanks!
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()
})();
This code is just a simple gallery and I wanna have the option to pause the loop when one clicks any picture in the gallery, display the clicked picture and restart the loop after 5 seconds.
setTimeout()is an asynchronous operation and works at the same time as the loop does. The callback function only runs when a) the amount of time specified has elapsed and b) the JavaScript runtime is idle, meaning that the current function (and its loop) have finished.