Frage

I need to create a special kind of script.
I want to show a message at certain times of the day. I've tested the code in Firebug Console and it works. The code is:

//Getting the hour minute and seconds of current time
var nowHours = new Date().getHours() + '';
var nowMinutes = new Date().getMinutes() + '';
var nowSeconds = new Date().getSeconds() + '';

var this_event = nowHours + nowMinutes + nowSeconds;
//172735 = 4PM 25 Minutes 30 Seconds. Just checked if now is the time
    if (this_event == "162530") {
        window.alert("Its Time!");
    }

I feel that the Script is not running every second. For this to work effectively, the script has to be able to check the hour minutes and second "Every Second". I'm not worried about the performance, I just have to be accurate about the timing (to the second).

How do I do this?

War es hilfreich?

Lösung

Of course the script isn't running each second, GM-scripts run once when the document has been loaded.

Calculate the difference between the current time and the target-time and use a timeout based on the difference:

var now=new Date(),
    then=new Date(),
    diff;
    then.setHours(16);
    then.setMinutes(15);
    then.setSeconds(30);
    diff=then.getTime()-now.getTime();

    //when time already has been reached
    if(diff<=0){
      window.alert('you\'re late');
    }
    //start a timer
    else{
     window.setTimeout(function(){window.alert('it\'s time');},diff);
    }

Andere Tipps

Javascript doesn't guarantee your timeouts and other such events fire exactly on-time.
You should compare two Date objects using >= and remove the timeout or what ever other method you're using for tracking the time inside the matching if (and then reset it if necessary).

For more details see: https://stackoverflow.com/a/19252674/1470607
Alternatively you can use string comparison (but with caveats): https://stackoverflow.com/a/6212411/1470607

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top