while true loop freezes up broswers javascript

不打扰是莪最后的温柔 提交于 2019-12-23 07:08:03

问题


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;
    }
}

回答1:


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

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

Try this:

var timeoutId = null;

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

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).

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);
}



回答2:


Your browser freezes up because JavaScript is single-threaded; it will ignore all inputs and events until the loop is done.

What you really want is something like this:

var x = 0; 
var nextImage= function () { 
    document.getElementById("img").src = images[x]; 
    x = (x + 1) % images.length;
}
setInterval(nextImage, 3000);

at each cycle, the code changes one image and quits, allowing other events to be handled.

BTW, I wasn't trying to write good JavaScript, just to answer your question.




回答3:


It's because you've intentionally created an infinite loop.

I'm not sure what other explanation you're after....

Your code will never reach the condition:

if (x=2)

because it never gets out of the loop. Provide some way to escape the loop. If your intention is to regularly cycle images then perhaps you should consider getting the images on a timer.

Also, your code implies there are an infinite number of images.



来源:https://stackoverflow.com/questions/16425483/while-true-loop-freezes-up-broswers-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!