javascript随机时间后重定向到网址

时间:2022-10-20 09:50:38

I have this javascript redirect script which works

我有这个javascript重定向脚本,它的工作原理

<p>You will be redirected in <span id="counter">120</span> second(s).</p>

<script type="text/javascript">
function countdown() {
    var i = document.getElementById('counter');
    if (parseInt(i.innerHTML)<=0) {
        location.href = 'http://example.com';
    }
    i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
</script>

My question is: How can I get a random number (e.g. between 60 and 120) instead of a fixed number before the script redirects?

我的问题是:如何在脚本重定向之前获取一个随机数(例如60到120之间)而不是固定数字?

1 个解决方案

#1


2  

Because Math.random() returns a number between 0 and 1, you basically have to multiply the result by the length of your interval - this will give you offset, which you then add to the beginning of the interval. The code will look like this:

因为Math.random()返回一个介于0和1之间的数字,所以你基本上必须将结果乘以你的间隔长度 - 这将给你偏移量,然后你将它添加到间隔的开头。代码如下所示:

var min = 60; 
var max = 120; 
var rnd = Math.floor(Math.random() * (max - min + 1)) + min;

#1


2  

Because Math.random() returns a number between 0 and 1, you basically have to multiply the result by the length of your interval - this will give you offset, which you then add to the beginning of the interval. The code will look like this:

因为Math.random()返回一个介于0和1之间的数字,所以你基本上必须将结果乘以你的间隔长度 - 这将给你偏移量,然后你将它添加到间隔的开头。代码如下所示:

var min = 60; 
var max = 120; 
var rnd = Math.floor(Math.random() * (max - min + 1)) + min;