emotions
emotions

Reputation: 3

Random number not updating in SetInterval function

I've tried a few different approaches to this found on SO but just cant seem to get it to work.

I'm trying to update the randomly selected item in an array, in a setInterval function, but the random number is not changing.

It is randomly chosen on first load, but then it doesn't update after the fact, each time the function runs again.

This is all using the lazylinepainter plugin: https://github.com/camoconnell/lazy-line-painter

var pathArray = [pathOne,pathTwo,pathThree,pathFour,pathFive,pathSix],
colors = ['#e51616','#0000FF','#FFFF00','#00FF00'],
drawBox = $('#drawing-box'),
svg = $('#drawing-box svg'),
svgPath = document.createElementNS("http://www.w3.org/2000/svg", "path");

function randomFrom(array) {
   return array[Math.floor(Math.random() * array.length)];
}

randomColor = randomFrom(colors);

var i = Math.floor(Math.random() * (5 - 0 + 1));
console.log(i);

function Draw(){

   var drawLoop = setTimeout(function (){
                    $('#drawing-box svg path').animate({'opacity':0},300);
                    setTimeout(function(){
                        $('#drawing-box svg path').remove();
                        drawBox.lazylinepainter('paint');
                        console.log(pathArray[i]);
                    },350);
                },5500);

   var drawFunc = drawBox.lazylinepainter({
                "svgData": pathArray[i],
                "strokeColor": randomColor,
                "strokeWidth": 5,
                "responsive": true,
                "onComplete": drawLoop
            });

   drawFunc.lazylinepainter('paint')
};

setInterval(function(){
   Draw();
},6000);

Here it is on jsFiddle —————

Rerun the fiddle over and over to see the different paths chosen at random (since its not updating otherwise).

Hopefully that snippet is clear, was still trying a few different things in there.

The ultimate goal is to have that line draw a randomly chosen item from the pathArray (pathOne, pathTwo, pathThree, etc. etc.) with each interval.

Upvotes: 0

Views: 301

Answers (1)

ced-b
ced-b

Reputation: 4065

Seems to me you are calling the actual function only once and then assigning it to randomColor which gets used over and over.

What you should do instead is call it where it is needed:

var drawFunc = drawBox.lazylinepainter({
            "svgData": pathArray[i],
            "strokeColor": randomFrom(colors),
            "strokeWidth": 5,
            "responsive": true,
            "onComplete": drawLoop
        });

That way you get a fresh one every time.

Upvotes: 1

Related Questions