javascript 函数运行时使JS函数输出

gzszwxb4  于 2023-02-21  发布在  Java
关注(0)|答案(1)|浏览(152)

Javascript代码

function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}

window.CP.PenTimer.MAX_TIME_IN_LOOP_WO_EXIT = 1000000;
var money = 0
var i = 0
let dollars = document.getElementById("total")
let dollarclick = document.getElementById("click1")
let autoclick = document.getElementById("buyauto")

dollarclick.addEventListener("click", clicked)
autoclick.addEventListener("click", auto)
function clicked() {
  money = money + 1
  dollars.innerHTML = "$"+ money.toString()
}
function auto() {
  autoclick.disabled = true
  console.log("function skull")
  while (i<10) {
    money = money + 1
    dollars.innerHTML = "$"+ money.toString()
    sleep(1000)
    console.log(money)
    i++
  }
}

如何让函数在运行时输出,而不是在函数运行结束后输出?记住我在做一个饼干点击器类型的游戏,自动只能购买一次。你能帮我解决这个问题吗?游戏应该每秒都能给予点,而不是在函数运行结束后。请帮帮我,谢谢!

hc2pp10m

hc2pp10m1#

您可以以异步方式执行此操作。
我使用了一个函数(setTimeoutAsyncfrom #3 here),它在超时后解析一个promise,还有一个异步递归函数(nClicks(n)),它在执行操作之前使用await作为超时,并在返回之前等待递归n次。
然后,异步事件处理器只需要禁用按钮,并等待nClicks(10)完成,然后再执行其他操作,如重新启用按钮。如果之后不需要执行其他操作,可以省略处理器上的async声明,只调用nClicks(10)而不调用await

const setTimeoutAsync = function(timeout) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, timeout)
  })
}

let money = 0
const dollars = document.getElementById('total')
const tick = () => {
  dollars.innerHTML = `$${++money}`
  console.log('tick', dollars.innerHTML)
}

const nClicks = async(n) => {
  if (n) {
    // wait one second
    await setTimeoutAsync(1000)
    // then incriment
    tick()
    // wait for recursion to complete
    await nClicks(--n)
  }
}

const dollarclick = document.getElementById('click1')
const autoclick = document.getElementById('buyauto')

dollarclick.addEventListener('click', tick)

autoclick.addEventListener('click', async() => {
  autoclick.disabled = true
  // wait for 10 cycles
  await nClicks(10)
  autoclick.disabled = false
})

const autoclickOnce = document.getElementById('buyautoOnce')
autoclickOnce.addEventListener('click', () => {
  autoclickOnce.disabled = true
  nClicks(10)
})
<h1 id="total">$0</h1>
<button id="click1">+1</button>
<button id="buyauto">Auto</button>
<button id="buyautoOnce">Auto Once</button>

相关问题