JavaScript超时重置机制

时间:2018-11-30 01:07:56

标签: javascript function settimeout onload cleartimeout

我想要的东西: 每三秒钟切换/交换两张图片。

我想这样做,以便在单击按钮时切换图片并重置自动交换。因此,如果单击该按钮,则会交换图像,三秒钟后,它将自动交换,直到再次单击该按钮,循环才会重复。

我现在拥有的东西 当前的问题是:单击按钮时,会弄乱自动切换的时间。

编辑: 请不要创建新的代码库。只需修改地雷。该代码不必是专家的超简明级别。我只有3周的时间学习JavaScript(这是我的第一门编程语言)。我必须向同学解释,如果代码中包含我不了解的元素,那就太不好了。很抱歉给您带来不便。

现在,我只需要按钮即可正确停止并重新开始时间。

<html>
<head>
    <script>
        let reset = setTimeout(change, 3000);
        function change() {
            if(document.getElementById("picture").src == "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350") {
                document.getElementById("picture").src = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350";
            }
            else {
                document.getElementById("picture").src = "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
            }
            setTimeout(change, 3000);
        }
        function fastChange() {
            clearTimeout(reset);
            if(document.getElementById("picture").src == "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350") {
                document.getElementById("picture").src = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350";
            }
            else {
                document.getElementById("picture").src = "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
            }
        }
    </script>
</head>
<body>
    <input type="button" onclick="fastChange();">
    <img src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350" id="picture">
</body>
</html>

4 个答案:

答案 0 :(得分:1)

重置计时器的原因是因为您没有清除超时。

您需要引用超时,然后在进行快速更改时在其上使用clearTimeout()。我认为以这种方式内联地进行操作是不可能或明智的,因此您的代码需要重构

let imgSrc1 = 'https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350'
let imgSrc2 = 'https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350'

let imgElement = document.getElementById('picture');
let timeout;

function change() {
   if(imgElement.src === imgSrc1) {
      imgElement.src = imgSrc2;
   } else {
      imgElement.src = imgSrc1;
   }
   if (timeout) {
      clearTimeout(timeout);
}

   timeout = setTimeout(change, 3000);
}

您甚至不需要第二个功能fastChange。现在,您可以像这样将onClick侦听器发送到change()

document.getElementById('无论您要单击什么').onCLick = change;

答案 1 :(得分:0)

您可以通过调用setTimeout并根据需要更新索引来做到这一点。只需确保存储最新的超时ID,以便可以使用clearTimeout在重置时将其取消。

// store the reference to the <img> that contains the picture
const pic = document.getElementById('picture')

// store a list (array) of the two picture urls
const sources = [
  'https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350',
  'https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350'
]

// used to store a reference to the interval timer you created.
var lastTimer
// a starting index of the list (i.e. which image we are up to right now)
var index = 1

// this functions swaps the image and sets a timer
function startRotation() {
  // update the index to the next one (goes 0-1-0-1->etc)
  index = 1 - index
  // sets the .src of the image element
  pic.src = sources[index]
  // starts a 3 second timer to call this same function again
  // but also stores a reference to the timer so that it can be cancelled
  lastTimer = setTimeout(startRotation, 3000)
}

// this functions resets the timer and restarts the process
function reset() {
  // stop the current timer if there is one
  if(lastTimer){
    clearTimeout(lastTimer)
  }
  // restart the process
  startRotation()
}

// start the swapping process on start
startRotation()
<input type="button" onclick="reset();">
<img id="picture">

答案 2 :(得分:0)

可以在多个位置设置和清除超时,但是我更喜欢使用“主循环”和变量来计数帧。

下面是使用setInterval并在单击按钮时重置timer变量的示例:

const url1 = "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
const url2 = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350";

function change() {
  picture.src = picture.src == url1 ? url2 : url1;
}

var timer = 0;

setInterval(function() {
  timer++;
  time.textContent = timer;
  if (timer === 30) fastChange();
}, 100);

function fastChange() {
  change();
  timer = 0;
}

picture.src = url1;
swap.onclick = fastChange;
#picture {
  height: 70vh
}
<button id="swap">SWAP</button> <span id="time"></span><br>
<img id="picture">

答案 3 :(得分:0)

您不清除超时:

<html>
<head>
    <script>
        var i;
        function change() {
            if(document.getElementById("picture").src == "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350") {
                document.getElementById("picture").src = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350";
            }
            else {
                document.getElementById("picture").src = "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
            }
            i = setTimeout(change, 3000);
        }
        function fastChange() {
            clearTimeout(i);
            if(document.getElementById("picture").src == "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350") {
                document.getElementById("picture").src = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350";
            }
            else {
                document.getElementById("picture").src = "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
            }
            i = setTimeout(change, 3000);
        }
    </script>
</head>
<body onload="setTimeout(change, 3000)">
    <input type="button" onclick="fastChange();">
    <img src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350" id="picture">
</body>
</html>