【问题标题】:How do I make a page no fall asleep when it is no focused on?当页面没有被关注时,如何使页面不入睡?
【发布时间】:2019-12-28 02:48:01
【问题描述】:

我正在制作一个答题器/大亨网页游戏,但是当页面没有被关注时,页面将不会处于活动状态,有没有办法让它在没有被关注时页面不会变得不活跃,或者有什么办法解决吗?

【问题讨论】:

  • setInterval 将始终在后台运行。如果您使用requestAnimationFrame,则在没有焦点时会停止。
  • @GetOffMyLawn 我正在使用这样的脚本来处理所有的金钱和时间,但是一旦标签不集中,它就会立即进入睡眠状态,window 部分是否搞砸了? window.setInterval(function() { //code }, 10);
  • 我读到一旦浏览器失去焦点,浏览器会将时间间隔缩短到1000ms。所以,要做的一件事是获取浏览器失去焦点的时间,然后获取它获得焦点的时间,然后做一些数学运算来检查已经过去了多少秒。然后你会根据数学更新他们的余额。

标签: javascript html focus


【解决方案1】:

浏览器的setInterval 在没有焦点时不会以最大速度运行,因此您需要获取窗口模糊/焦点事件并自己进行数学运算。这是如何完成的示例。单击窗口创建焦点,然后在窗口上短暂取消焦点,然后再次赋予窗口焦点(重复)。

注意:不要忘记在原始循环中停止提供现金,否则您将计算不止一次并提供额外的现金。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多