setTimeOut没有等待适当的延迟时间

时间:2012-07-30 06:44:29

标签: javascript jquery

我有两个按钮播放并停止。当我点击播放时,我希望图像像幻灯片一样运行。 我正在使用setTimeout()并在运行前等待5秒钟。

单击播放时,代码运行正常,等待5秒然后显示下一个图像,但是当我单击停止,然后再次单击播放时,它将停止等待正确的间隔。而不是等待5秒钟运行时,前两个图像等待一秒钟,下一个图像等待5秒钟,接下来两个等待一秒钟等等......

为什么第一次正确运行然后重试?

代码:

var stop = false;
playClickfunction() {
    showImages();
}
showImages() {
    //code to display image for all no of images
    //and user can stop on any no of image..
    if(!stop)
       setTimeout(showImages, 5000);
}

stopClickfunction() {
   stop = true;
}

4 个答案:

答案 0 :(得分:1)

你需要在停止时清除超时。

也许尝试类似的东西:

var timer = false;

playClickfunction()
{
    showImages();
}

showImages()
{

    //code to display image for all no of images
    //and user can stop on any no of image..
    if(!stop)
       timer = setTimeout(showImages, 5000);
}

stopClickfunction()
{

   clearTimeout( timer )
}

答案 1 :(得分:1)

尝试使用正确的方式而不是使用标志变量

var timer = setTimeout(showImages, 5000);
clearTimeout(timer);

答案 2 :(得分:0)

你应该使用clearTimeOut()方法

答案 3 :(得分:0)

如果单击“停止”,则在5秒钟之前再次单击“启动”,第一个超时将继续运行。您需要做的是清除超时,而不仅仅是停止图像,但每次点击开始时,例如:

var timeout;

function start() {
    stop();
    showImages();
  }
}

function stop() {

  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
}

function showImages() {
  // do stuff, then
  timeout = setTimeout(showImages, 5000);
}

或者,如果单击start并设置超时,则忽略该单击,因为计时器已在运行。在那种情况下你会这样做:

function start() {
  if (!timeout) {
    showImages();
  }
}
相关问题