简体   繁体   English

如何定期检查页面状态而不刷新?

[英]How do I regularly check the state of a page without refreshing?

I'm pretty new to (javascript) programming and I'm trying to get something automated. 我对(javascript)编程非常陌生,并且正在尝试使某些东西自动化。

There is a page that contains a countdown timer, and I want my greasemonkey script to automatically do some actions if the condition is met. 有一个页面包含一个倒数计时器,如果条件满足,我希望我的lublessmonkey脚本自动执行一些操作。

I've got this right now: 我现在有这个:

var timer = document.getElementById('timer_4975');

if (timer.innerHTML < "00:00:20"){
//Some actions
}

But this only checks the condition once when the script is loaded, when the timer goes under 00:00:20, it doesn't detect the condition is met and doesn't go to action. 但这仅在脚本加载时检查一次条件,当计时器在00:00:20以下时,它不会检测到条件已满足且不会执行操作。

Can someone guide me in the right direction? 有人可以指引我正确的方向吗?

Thanx in advance! 提前感谢!

You will have to use setInterval() to execute your code more than once: 您将不得不使用setInterval()多次执行代码:

setInterval(function() {
    if(timer.innerHTML < "00:00:20") {
        //Some actions
    }
}, 5000); //Execute this function each 5 seconds.

You can use the setTimeout or setInterval functions to perform this task. 您可以使用setTimeoutsetInterval函数执行此任务。

setInterval will perform a task regularly, which is probably more suited to what you want to achieve. setInterval将定期执行任务,这可能更适合您要实现的任务。

Something like: 就像是:

var timer = document.getElementById('timer_4975');

var intervalHandle = setInterval(function() {
  if (timer.innerHTML < "00:00:20"){
  //Some actions
  clearInterval(intervalHandle);
  }
},1000);

would check every second (1000ms). 将每秒检查一次(1000毫秒)。 Change the 1000 value to increase or decrease the frequency of checking... once a second is likely to be often enough. 更改1000值以增加或减少检查的频率...每秒可能足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM