setInterval()无法正常工作 - 以指数方式增加

时间:2015-03-23 22:15:33

标签: javascript

<!DOCTYPE html>
<html>
<head> 
<title> Cookie Clicker! </title>
<script type="text/javascript">
var logAt=function(id,message){
document.getElementById(id).innerHTML=message;
};
</script>
</head>
<body>
<h1 class="center" style="text-align:center"> Cookie Clicker </h1>
<p class="center" id="para1" style="text-align:center;"> Keep collecting cookies and start your very own sweet empire!</p>
<p>
<div class="center" id="cookiesPerSecond" style="text-align:center"> </div>

<button id="getACookie" type="button" onClick="getCookie()"><image src="http://blog.speekee.com/wp-content/uploads/2014/09/Cookie.gif" 
style="width:300px;height:300px;align:middle"></button> 
<h3 id="cookies" style="text-align:center;">Cookies:0 </h3>

</p>
<h2 id="store"> Store</h2>
<p>
<button type="button" onClick="getOven()"> Buy another oven! <image 
src="http://products.geappliances.com/MarketingObjectRetrieval/Dispatcher?RequestType=Image&Name=0107108.jpg" style="width:50px;height:50px"> </button>
</p>
<div id="oven"> <strong> 90 Cookies </strong> An extra oven <br> will give you half a cookie <br> per second</div>
<style>
#getACookie{
display: block;
margin-left: auto;
    margin-right: auto;
}


</style>

<script type="text/javascript">
var cookies=0;
var cookiesPerSecond=0;
function getCookie(){
cookies+=1;
logAt("cookies","Cookies:"+cookies);
};
var getOven=function(){
if(cookies>=10){
cookies=cookies-90
cookiesPerSecond+=0.5;
logAt("cookiesPerSecond","Cookies per second:"+cookiesPerSecond);
setInterval(function(){
cookies+=cookiesPerSecond;
logAt("cookies","Cookies:"+cookies);},1000);
}
else{
alert("You do not have enough cookies!");
}
};


</script>
</body>
</html>

当烤箱不止一次(在#34; getOven&#34;功能中)而不是每秒一个cookie时,它会增加2个饼干,等等。这是我的变量的问题吗?我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

您需要在开始新的间隔之前清除之前的间隔。请参阅下面的修改后的代码示例:

var cookies=0;
var cookiesPerSecond=0;
var interval = null; //Declare a variable to hold a reference to the interval
function getCookie(){
  cookies+=1;
  logAt("cookies","Cookies:"+cookies);
};

var getOven=function(){
  if(cookies>=10){
    cookies=cookies-90
    cookiesPerSecond+=0.5;
    logAt("cookiesPerSecond","Cookies per second:"+cookiesPerSecond);

    // Check if a previous interval has been set, if so clear it.
    if (interval != null) {
      clearInterval(interval);
    }

    // Finally, set a new interval and store a reference to it in the variable
    interval = setInterval(function(){
      cookies+=cookiesPerSecond;
    logAt("cookies","Cookies:"+cookies);},1000);
  }
  else{
  alert("You do not have enough cookies!");
  }
};