如何在javascript中重置变量

问题描述 投票:1回答:4

这是代码

var x = Math.floor( Math.random() * 10 );
setInterval(function () {

    if (x >= 5) {
          $('.test').show();
          setTimeout(function () {
                         $('.test').hide();
                 }, 2000);
    } else {
        x = Math.floor( Math.random() * 10 );
    }

}, x * 1000);

这个代码显示.test具有相同的随机,如果x=8它将保持8并且不会改变我真正想要的是将x更改为另一个数字

我试图将var x放在本地范围内,它显示我在x中的setInterval是一个未定义的

我希望$('.test')以5到10秒之间的随机方式显示,就像7S后的第一次演出和9秒后的第二次演出等等。

javascript if-statement math random
4个回答
0
投票

每次显示的延迟与此代码段不同。

function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

function showDiv(x){
  setTimeout(function () {
    $('.test').show();
    setTimeout(function () {
      $('.test').hide();
      x = getRandomArbitrary(5, 10)
      showDiv(x)
    }, 2000);
  }, x * 1000);
}

var x = getRandomArbitrary(5, 10)
showDiv(x)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test" style="display: none">test</div>

0
投票

使用setTimeout,setInterval只会以您第一次调用它的间隔运行。 setTimeout只触发一次,然后你可以用另一个随机变量再次调用它。

roll();

function roll() {
  var x = Math.floor( Math.random() * 10 );
  setTimeout(function () {
    if (x >= 5) {
      $('.test').show();
      setTimeout(function () {
        $('.test').hide();
      }, 2000);
    }
    roll();
  }, x * 1000);
}
.test {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">Test div</div>

0
投票

我建议重新安排你的代码并创建一个用setTimeout()调用自己的函数。为此遗忘setInterval() ...就像评论中提到的epascarello一样,clearInterval()的第二个参数(间隔的毫秒数)将在代码开始运行时配置一次,并且每隔N毫秒调用该函数,其中N是最初配置的间隔。

var x = Math.floor( Math.random() * 10 );

function test(x)
{
    console.log(x);

    if (x > 5)
    {
        $('.test').show();
        setTimeout(() => $('.test').hide(), 2000);
    }

    x = Math.floor( Math.random() * 25 );
    setTimeout(() => test(x), x * 1000);
}

test(x);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test" style="display:none; background:skyblue">TEST</div>

0
投票
var x = Math.floor( Math.random() * 10 );
setInterval(function () {

    if (x >= 5) { // because of this, you get the same number for x. if x >= 5 then the x won't change in this block and has the last value forever.
          $('.test').show();
          setTimeout(function () {
                         $('.test').hide();
                 }, 2000);
    } else {
        x = Math.floor( Math.random() * 10 );
    }

}, x * 1000);
© www.soinside.com 2019 - 2024. All rights reserved.