javascript 变量未被新值除[重复]

dojqjjoe  于 2023-05-12  发布在  Java
关注(0)|答案(1)|浏览(119)

此问题已在此处有答案

Changing the interval of SetInterval while it's running(17回答)
7小时前关闭
我正在尝试制作一个点击游戏,我正在为每个点击游戏划分一个新的点击(货币)的等待时间,但它是不工作,即使变量正在更新。
这是我的代码

var clickers = 1;
var x = 0;

function fun() {
  x = x + 1;
  const element = document.getElementById("id01");
  element.innerHTML = x;

}
function myFunction() {
  var number = x;
  document.getElementById("myText").innerHTML = number;
}

//here is how we will buy auto clickers, and how they work

function buyClicker() {
  clickers += 1;
  alert(clickers)
  x -= 20;
  const element = document.getElementById("id01");
  element.innerHTML = x;
}

window.setInterval(function() {
  x = x + 1;
  const element = document.getElementById("id01");
  element.innerHTML = x;
}, 1000 * clickers);
<!DOCTYPE html>
<html>

<head>
  <body onload="myFunction()">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <script src="script.js"></script>
</head>

<body>
  <h1 id="id01"> The value for number is:  <span id="myText"></span></h1>
  <h1>HERE IS OUR GAME :D</h1>

<button id="demo" onclick="fun()">make clicks</button>
<button id="demo" onclick="buyClicker()"> buy clicker</button>

我试图添加到这个变量随着时间的推移,等待时间减少每一次,但不会减少

rsaldnfx

rsaldnfx1#

我不确定,但我希望它能解决你的问题。更新每个点击器的等待时间就是清除间隔,然后用新的等待时间重新设置它。

let clickers = 1;
let x = 0;
let intervalId = null;
let waitTime = 1000;

function fun() {
  x = x + 1;
  const element = document.getElementById("id01");
  element.innerHTML = x;
}

function myFunction() {
  var number = x;
  document.getElementById("myText").innerHTML = number;
}

function buyClicker() {
  clickers += 1;
  x -= 20;
  waitTime /= 1.1; // Reduce the wait time by 10% for each new clicker
  const element = document.getElementById("id01");
  element.innerHTML = x;
  
  clearInterval(intervalId); // Clear the current interval
  intervalId = setInterval(function() {
    x = x + clickers;
    const element = document.getElementById("id01");
    element.innerHTML = x;

  }, waitTime);
}

intervalId = setInterval(function() {
  x = x + clickers;
  const element = document.getElementById("id01");
  element.innerHTML = x;

}, waitTime);

相关问题