javascript - 写函数不读定时器

标签 javascript timer

我正在尝试编写一个计时器函数。在第一个状态下,计时器可以工作,但它执行的代码必须分别放置在计时器内的 goActive/goInactive 函数内。现在,我尝试通过让 goActive/goInactive 返回小信号变量(其他代码块可以解释这些变量)来将计时器与函数调用分开。

现在我只有一个简单的模型。我希望 goActivegoInactive 返回 1 或 -1,然后另一个函数 checktimer 应该在更新时将它们写入屏幕。但我还没弄清楚其中的逻辑。我对 JS 很陌生;我感谢所有帮助:

var TimeoutID;
var timerstatus = 0;

function inputdetect() {
  // attaches event handler to specified event
  // takes event as string, function to run, and optional boolean
  // to indicate when the event propogates
  // these are false, so events "bubble up"
  this.addEventListener("mousemove", resetTimer, false);
  this.addEventListener("mousedown", resetTimer, false);
  this.addEventListener("mousewheel", resetTimer, false);
  this.addEventListener("keypress", resetTimer, false);
  this.addEventListener("touchmove", resetTimer, false);
  this.addEventListener("DOMmousescroll", resetTimer, false);
  this.addEventListener("MSpointermove", resetTimer, false);

  startTimer();
}

inputdetect();

function startTimer() {
  //waits two seconds before calling inactive
  TimeoutID = window.setTimeout(goInactive, 2000); // does it need to take the window variable??
}

function resetTimer(e) {
  window.clearTimeout(TimeoutID);
  goActive();
}

function goActive() {
  //what happens when the UI is not idle

  $('#hi').text("The UI is not idle.");
  timerstatus = 1;
  $('#var').text(timerstatus);

  startTimer();
  return timerstatus;
}

function goInactive() {
  $('#hi').text("The UI is idle.");
  timerstatus = -1;
  $('#var').text(timerstatus);
  return timerstatus;
  // REPLACING CURSOR WHEN UI IS IDLE
  //this part won't work
}

function checktimer(timerstatus) {
  $('#ct').text(timerstatus);
}

$(document).ready(function() {
  window.setInterval(checktimer(timerstatus), 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div>check timer update goes: <span id="ct"></p></div>

<!--this is where the HTML will go*/-->
<p id = "hi">hello</p>
<p id = "ts">Timer status is: <span id = "var"></span> 
  </p>

最佳答案

这是不正确的。

window.setInterval(checktimer(timerstatus), 2000);

您需要传递一个函数而不是调用一个函数。

因为timerstatus是一个全局变量,它已经被所有函数共享,所以你不需要传递和返回它。所有功能都可以直接使用。

因此只需将 checktimer 传递给 setInterval 即可。

window.setInterval(checktimer, 2000);

删除所有 returntimerstatus; 行,并删除 checktimer 的参数:

function checktimer() {
  $('#ct').text(timerstatus);
}

我不知道这是否符合您最终想要的,但它确实纠正了代码。

关于javascript - 写函数不读定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31493127/

相关文章:

javascript - 如何获取 limit 和降序 created_At 返回的项目索引

java - 如何使用计时器制作 Activity 弹出窗口

javascript - PHP 计时器等待 30 秒然后运行命令

java - Java 中的计划任务 - 使用哪个工具

C# 定时器不工作

javascript - React Native 将状态设置为 true 一秒钟

javascript - tinyMCE 编码 HTML 标签

javascript - Postman 测试中的 If 语句

javascript - 子主题后插件不工作

javascript - node.js,setTimeout回调方法和 "this"