Javascript random images + back button

时间:2018-04-20 01:15:07

标签: javascript

I'm trying to create a site where it randomly chooses a photo from an array, then the user can use the arrow keys to press next and load another random image, if they press back it loads the previous image. I have all of this working:

Only problem is when I press next the # of times = to the length of the array, I get an error that says Maximum call stack size exceeded.

How do I fix?

Code:

var rand = imagesArray[Math.floor(Math.random() * imagesArray.length)];
var theImg = document.getElementById('gif');
theImg.src=rand;
theImg.height = 700;
theImg.width = 1920;
var usedImages = {};
var usedImagesCount = 0;
var numHistory = [];

function displayPreviousImage(){
    if (numHistory.length > 1){
      numHistory.pop();
      var num = numHistory[numHistory.length-1];
      document.canvas.src = imagesArray[num];
    }
}

function displayNextImage(){

    var num = Math.floor(Math.random() * (imagesArray.length));

    if (!usedImages[num]){
        numHistory.push(num);
        document.canvas.src = imagesArray[num];
        usedImages[num] = true;
        if (usedImagesCount === imagesArray.length){
            usedImagesCount = 0;
			num = 0;
            usedImages = {};
			console.log("done")
        }
    } else {
        displayNextImage();
    }
}

1 个答案:

答案 0 :(得分:0)

usedImages具有数组中所有可能的索引时,您的函数将进行无限循环。还有另一种解决方案,对您来说更容易,首先让我们对图像数组进行随机播放,然后让用户通过0-n的新顺序浏览它。这样你仍然可以随机提供图像,但不需要跟踪使用过的图像。

function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

 return array;
}