gpt4 book ai didi

javascript - setInterval() 无法正常工作 - 呈指数增长

转载 作者:行者123 更新时间:2023-12-03 10:30:54 26 4
gpt4 key购买 nike

<!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>

当多次获取 toastr 时(在“getOven”函数中),它不是每秒 1 个 cookie,而是每秒添加 2 个 cookie,依此类推。这是我的变量有问题吗?我应该做什么来修复它?

最佳答案

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

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!");
}
};

关于javascript - setInterval() 无法正常工作 - 呈指数增长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29221467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com