如何让页面在不被关注的情况下不睡着?

How do I make a page no fall asleep when it is no focused on?

我正在制作一个 clicker/tycoon 网页游戏,但是当页面没有被聚焦时,页面将不会处于活动状态,有没有什么办法可以使页面不处于活动状态,如果没有专注于,或者有什么办法解决它?

当没有焦点时,浏览器的 setInterval 不会以最大速度 运行,因此为了解决这个问题,您需要获取 window blur/focus 事件和自己算算。这是如何完成的示例。单击 window 创建焦点,然后在 window 上短暂取消焦点,然后再次给予 window 焦点(重复)。

注意:不要忘记在原来的循环中停止给现金,否则你会不止一次计算并给额外的现金。

// The current balance
let balance = 0
// The time the window lost focus
let focusLostTime = null
// The amount of cash per second
let cashPerSec = 2
// Wheter we should calc balance in the main loop
let calcBalance = true
// The output 
let balanceOutput = document.getElementById('balance')

window.addEventListener('blur', () => {
  // Set the time the window lost focus
  focusLostTime = Date.now()
  calcBalance = false
})

window.addEventListener('focus', () => {
  // If this hasn't been set don't do anything
  if(!focusLostTime) return
  calcBalance = true
  // Calculate the elapsed time 
  // This will be in seconds and posibly have a decimal
  let elapsedTime = (Date.now() - focusLostTime) / 1000
  // Multiply the elapsed time by the amount of cash they get per second
  balance += elapsedTime * cashPerSec
  
})

////////////////////////////////////////
// This is just for example update loop
////////////////////////////////////////

// When the last tick was
let lastTick = Date.now()

setInterval(() => {
  if (!calcBalance) return
  let elapsedTime = (Date.now() - lastTick) / 1000
  balance += cashPerSec * elapsedTime
  lastTick = Date.now()
  balanceOutput.innerText = balance
}, 10)
Balance: <span id="balance"></span>