dimanche 30 avril 2017

how to make multiple instances in JavaScript

i was trying to generate random numbers to pick random items from array to update collage of pictures, i noticed that sometimes generated number is same to a previously generated number causing one picture to update 2-3 times so to check this i thought it would be great if i store last generated random number into an variable and make a function that checks if last generated value is equal to current generated value, it continue to generate numbers till a non-equal value is generated.

it is working fine until i wanted multiple instances ... as variable that stores last value is same, i am getting same numbers.

var bgs = document.getElementById('collage').getElementsByClassName('bg');
var images = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var lv = null;
function get_random(length) {
    arr = [];
    while (arr.length < 1) {
        var cv = Math.floor(Math.random() * length);
        if (lv === cv) {
            arr = [];
            continue;
        }
        else if (lv !== cv) {
            arr.push(cv);
            break;
        }
    }
    lv = arr[0];
    return arr[0];
}

function update_collage() {
    var img = images[get_random(images.length)];
    var target = bgs[get_random(bgs.length)];
    target.style.background = "url('assets/img/thumbs/" + img + ".jpg') no-repeat center";
    target.style.backgroundSize = "cover";
}
window.setInterval(function(){
    update_collage();
}, 1200);

how can i correct this, how can i create multiple instances of function or variable




Aucun commentaire:

Enregistrer un commentaire