简体   繁体   中英

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.

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.

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.

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(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.

setInterval will perform a task regularly, which is probably more suited to what you want to achieve.

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). Change the 1000 value to increase or decrease the frequency of checking... once a second is likely to be often enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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