而真正的循环冻结了broswers javascript [英] while true loop freezes up broswers javascript

查看:182
本文介绍了而真正的循环冻结了broswers javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图让图像改变并使它们成为一个循环,我想出了这个脚本,而我遇到的问题是,当它改为第二张图片时,javascript会冻结在我身上,我知道它虽然(真)部分,但我不知道如何解决它,请帮助。
谢谢你

so im trying to make the images change and make them into a loop and i came up with this script, and the problem i am having is that, when it change to the second picture the javascript would freeze up on me, I know it the while(true) part but i dont know how to fix it, please help.
thanks you

var images = new Array();
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 3000);
var x=0;

function changeImage()
{
    while(true){
        document.getElementById("img").src=images[x]
        x++;
    }

    if (x=2){
        x=0;
    }
}


推荐答案

啊,我明白你要做什么。

Ah, I see what you're trying to do.

而(true)将永远循环同步。你想要的是每3秒不断更换图像(异步)。

while (true) is going to loop forever synchronously. What you want is to continually change images every 3 seconds (asynchronously).

试试这个:

var timeoutId = null;

function changeImage() {
  document.getElementById("img").src = images[x];
  x = (x + 1) % images.length;
  timeoutId = setTimeout(changeImage, 3000);
}

这样, changeImage 永远不会循环;但是每次调用它都会在3秒钟内安排另一次调用 changeImage 。此异步过程将无限期地继续(您尝试使用而(true)),直到用户离开页面或您选择调用 clearTimeout (timeoutId)

This way, changeImage will not loop forever; but every time it's called it will schedule another call to changeImage in 3 more seconds. This asynchronous process will continue indefinitely (what you were trying to do with while (true)) until the user leaves the page or you choose to call clearTimeout(timeoutId).

请注意,您还可以摆脱全局变量 x 将它作为 changeImage 的参数,如下所示:

Note that you could also get rid of the global variable x by making it a parameter to changeImage, like this:

function changeImage(x) {
  document.getElementById("img").src = images[x];
  timeoutId = setTimeout(function() {
    changeImage((x + 1) % images.length);
  }, 3000);
}

这篇关于而真正的循环冻结了broswers javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆