【问题标题】:Random number not updating in SetInterval functionSetInterval 函数中未更新的随机数
【发布时间】:2015-02-27 06:44:00
【问题描述】:

我已经尝试了一些在 SO 上找到的不同方法,但似乎无法让它发挥作用。

我正在尝试在 setInterval 函数中更新数组中随机选择的项目,但随机数没有改变。

在第一次加载时随机选择,但事后不会更新,每次函数再次运行时。

这都是用lazylinepainter插件: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);

这里是jsFiddle————

一遍又一遍地重新运行小提琴以查看随机选择的不同路径(因为它不会更新)。

希望 sn-p 很清楚,仍在尝试一些不同的东西。

最终目标是让这条线在每个间隔从 pathArray(pathOne、pathTwo、pathThree 等)中随机选择一个项目。

【问题讨论】:

    标签: javascript jquery arrays random setinterval


    【解决方案1】:

    在我看来,您只调用了一次实际函数,然后将其分配给randomColor,它会被一遍又一遍地使用。

    你应该做的是在需要的地方调用它:

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

    这样你每次都能得到一个新的。

    【讨论】:

    • 好吧,我在获取随机颜色 (randomColor) 和获取随机路径 (pathArray) 之间尝试了两种不同的方法。我想如果我在 Draw 函数中调用它们,它们会更新,但似乎不是......应该全部包含在 Draw 函数中吗?
    • 在这两种情况下,您都在Draw() 函数之外调用Math.random(),因此它会在页面启动时被调用一次,并且永远不会再次调用。所以你必须在函数中调用它。
    • Ahhhhh 好的,我已经通过在区间内包含 Math.random() 函数来更新代码。我正在将随机 # 写入 console.log,它们现在肯定在更新,但绘制的线本身并没有改变……知道为什么会这样吗?更新小提琴:jsfiddle.net/gmrx8x2h/2
    • 不幸的是,我没有太多时间详细介绍这一点,但似乎你必须以某种方式 destroy 然后重新创建插件才能让它进入一种不同的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    相关资源
    最近更新 更多