setInterval() 更改图像

setInterval() change image

本文关键字:图像 setInterval      更新时间:2023-09-26

目标:加载页面时,andy_black.jpg显示图像。两秒钟后,将图像源和浏览器中的 thus 图像更改为名为 andy_white.jpg 的第二个图像。这将每 2 秒来回更改一次。

我查看了这篇文章:设置间隔函数调用

(我也搜索了其他标签[javascript] [function]和单词"setinterval",但大多数都使用jQuery,我在这里的目的不是使用任何jQuery,毕竟这是JavaScript的实验(。

这在我阅读它之前非常有用,我的代码要长得多,并且该函数没有在 setInterval(( 函数中调用。

所以这里有一些代码:建议?

var i = 1;
function change_pic() {
  i + 1;
  if (i == 5) {
    i = 1;
  }
  //I suspect the computer will read i as 5 for some
  //tiny amount of time before reverting back to 1
  //which I suspect could cause a further problem, but
  //is it the source of the current issue?
  if (i == 1 || i == 2) {
    document.getElementById('img_to_flip').src = "https://cdns-images.dzcdn.net/images/artist/5d9e44027cc266260d7bd932d98f739d/500x500.jpg";
  } else {
    document.getElementById('img_to_flip').src = "https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg";
  }
}
var pic_src = setInterval(change_pic, 2000);
<img id="img_to_flip" src="https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg" height="100" width="100" />

您忘记将新值实际重新分配给i

使用以下任一用途:

i = i + 1;

++i;

另外,当你只有两个州时,为什么要数到五? 使用自动重置计数器的常见范例是使用算法:

i = (i + 1) % 2;

这保证了i将永远只有 01 的值。

FWIW,这是一种编写整个功能的替代方法,适用于任意数量的图像 - 只需填充pics数组:

(function() { // function expression closure to contain variables
  var i = 0;
  var pics = ["https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg", "https://cdns-images.dzcdn.net/images/artist/5d9e44027cc266260d7bd932d98f739d/500x500.jpg"];
  var el = document.getElementById('img_to_flip'); // el doesn't change
  function toggle() {
    el.src = pics[i]; // set the image
    i = (i + 1) % pics.length; // update the counter
  }
  setInterval(toggle, 2000);
})(); // invoke the function expression
<img id="img_to_flip" src="https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg" height="100" width="100" />

如果要避免第一次 setInterval 的延迟,请在 setInterval 之前调用函数,如顶部答案所示:

(function() {     // function expression closure to contain variables
    var i = 0;
    var pics = [ "andy_white.jpg", "andy_black.jpg" ];
    var el = document.getElementById('img_to_flip');
    function toggle() {
        el.src = pics[i];           // set the image
        i = (i + 1) % pics.length;  // update the counter
    }
    toggle()
    setInterval(toggle, 2000);
})();             // invoke the function expression