SetTimeout难度

时间:2013-11-16 19:52:05

标签: javascript timer settimeout

我想创建一个允许我的页面随机刷新(15分钟到30分钟)的脚本。这是我到目前为止的代码:

<!DOCTYPE html>
<html>
<body onload="startCount()">


<input type="text" id="txt" style="visibility:hidden;">

<script>
var c = 0;
var t;
var timer_is_on = 0;

function timedCount()
{
document.getElementById("txt").value=c;
c = c+1;
if(c==10)  //if timer is 10 seconds ->refresh
location.reload();
t = setTimeout(function(){timedCount()},1000);
}

function startCount()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>

</body>
</html>

如果我像这样if(c==10)保持if,这是完美的,但为了让时间随机我修改它像这样:

<!DOCTYPE html>
<html>
<body onload="startCount()">


<input type="text" id="txt" style="visibility:hi;">

<script>
var c = 0;
var t;
var timer_is_on = 0;

function timedCount(number)
{
document.getElementById("txt").value=c;
c = c+1;
if(c==number)
location.reload();
t = setTimeout(function(){timedCount()},1000);
}

function startCount()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  var rand=Math.floor(Math.random() * (max - min + 1)) + min;
  timedCount(rand);
  }
}


</script>

</body>
</html>

但第二个不会工作......我不知道为什么......请帮助! :)

1 个答案:

答案 0 :(得分:0)

您错过了maxmin变量分配。

var min = 1;
var max = 10;
var rand = Math.floor(Math.random() * (max - min + 1)) + min;

alert()示例:http://jsfiddle.net/ZLcrX/

jQuery DOM示例:http://jsfiddle.net/ZLcrX/1/