javascript - 用 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 文件中
解决方案
而不是 a setInterval
,setTimeout
用于下一次运行
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
从任何其他功能设置为其他内容。这是最简单的方法,可以使用改进,例如不允许任何其他函数更改该值,但它应该可以解决您的问题
推荐阅读
- fortran - 有没有办法从导入的模块中找到使用了哪些过程/类型?
- ios - 在 Swift 中将数组转换为字典
- android - 使用 Firebase Auth 进行身份验证时,短信验证码请求失败
- git - 这个 git 图标在书呆子字体中是什么意思?
- javascript - JS history.pushState 问题“跳过斜线”
- .net-core - 使用 Nullable DateTime 属性反序列化 JSON 会引发 Newtonsoft.Json.JsonReaderException
- apache-kafka - Kafka Streams:使用 Spring Cloud Stream 为每组主题定义多个 Kafka Streams
- c++ - 'cppcoreguidelines-interfaces-global-init' 仅在特定情况下出错
- https - Apache2 作为简单的 https 代理
- kubernetes - 获取 API 组资源失败