setInterval,点击一些东西然后clearInterval,然后几秒钟再次setInterval

setInterval, click something then clearInterval, and then few seconds setInterval again

我想创建一个 运行ning 使用 setInterval 的滑块图像,当我单击缩略图时,图像滑块停止,但几秒钟后我希望它继续 运行 setInterval再次,我被困在这里。不知道怎么写代码让setInterval 运行s again

//auto animate
let counter = 0;
function imageChange() {
  bigImage.src = thumb[counter++].src;
  if(counter >= thumb.length) {
    counter = 0;
  }
}
let gallery = setInterval(imageChange, 1000);
//click thumb stop Animate then runs again
for(t of thumb) {
  t.addEventListener('click', (e) => {
    bigImage.src = e.target.src;
    clearInterval(gallery);
    //I'm stuck here :(
  });
}
pause = setTimeout(() => { gallery = setInterval(imageChange, 1000)} ,3000);

像这样

let pause;
//auto animate
let counter = 0;
function imageChange() {
  bigImage.src = thumb[counter++].src;
  if(counter >= thumb.length) {
    counter = 0;
  }
}
let gallery = setInterval(imageChange, 1000);
//click thumb stop Animate then runs again
for(t of thumb) {
  t.addEventListener('click', (e) => {
    bigImage.src = e.target.src;
    clearInterval(gallery);
    clearTimeout(pause);
    pause = setTimeout(() => { gallery = setInterval(imageChange, 1000)} ,3000);
  });
}

不过我会委派

let pause;
//auto animate
let counter = 0;
function imageChange() {
  bigImage.src = thumb[counter++].src;
  if(counter >= thumb.length) {
    counter = 0;
  }
}
let gallery = setInterval(imageChange, 1000);
//click thumb stop Animate then runs again
document.getElementById('thumbContainerId').addEventListener('click',function(e) {
  bigImage.src = e.target.src;
  clearInterval(gallery);
  clearTimeout(pause);
  pause = setTimeout(() => { gallery = setInterval(imageChange, 1000)} ,3000);
});

您不能暂停 setInterval 函数,您可以停止它 (clearInterval),或者让它 运行。

点击的时候把isPaused设为true即可。关闭缩略图时将 isPaused 设置为 false。

//auto animate
let counter = 0;
let isPaused = false;
function imageChange() {
  if(isPaused){
    return;
  }
 //Your code
}
let gallery = setInterval(imageChange, 1000);
//click thumb stop Animate then runs again
for(t of thumb) {
  t.addEventListener('click', (e) => {
    bigImage.src = e.target.src;
    isPaused = true;
  });
}

function closeThumnail(){
  isPaused = false;
}