首页 > 解决方案 > 用 JavaScript 中的条件检查间隔

问题描述

我有一个每 300 毫秒检查一次焦点的功能,当我按下一个按钮以激活另一个功能时,我需要这个功能跳过一次,然后如果我没有按下这个按钮,它就可以正常工作。

function checkPageFocus() {

    let body = document.querySelector('body');
    let log = document.getElementById('log');

    if (document.hasFocus()) {
        log.textContent = 'This document has the focus.';
        body.style.background = '#fff';
    } else { 
        alert("lost foucs");
    }

}

inter = setInterval(checkPageFocus, 300);

我按下按钮调用的第二个功能是

function myFunction(){

    window.parent.Popup.closeLast();

}

我需要使第一个函数每次都能正常工作,300ms 但如果我调用myfunction它,我需要它有一个间隔,1000ms然后开始正常工作,我试图在 setInterval 中传递一个变量,但它只每 300 毫秒工作一次,两者函数在同一个 .js 文件中

标签: javascript

解决方案


而不是 a setIntervalsetTimeout用于下一次运行

let interval = 1000;

function checkPageFocus() {

  let body = document.querySelector('body');
  let log = document.getElementById('log');

  if (document.hasFocus()) {
    log.textContent = 'This document has the focus.';
     body.style.background = '#fff';
  } else { 
      alert("lost foucs");
  }

  setTimeout(checkPageFocus, interval);
}

现在您可以interval = 300从任何其他功能设置为其他内容。这是最简单的方法,可以使用改进,例如不允许任何其他函数更改该值,但它应该可以解决您的问题


推荐阅读