【问题标题】:Create a scheduled Greasemonkey script创建一个预定的 Greasemonkey 脚本
【发布时间】:2014-05-12 08:39:03
【问题描述】:

我需要创建一种特殊的脚本。
我想在一天中的特定时间显示一条消息。我已经在 Firebug 控制台中测试了代码并且它可以工作。代码是:

//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!");
    }

我觉得脚本不是每秒都在运行。为了使其有效工作,脚本必须能够检查小时分钟和秒“每秒”。我不担心表现,我只需要准确的时间(到秒)。

我该怎么做?

【问题讨论】:

    标签: javascript greasemonkey userscripts


    【解决方案1】:

    当然,脚本不是每秒都在运行,GM 脚本会在文档加载后运行一次。

    计算当前时间和目标时间之间的差异,并根据差异使用超时:

    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);
        }
    

    【讨论】:

    • 非常感谢 Molle 博士。我以不同的方式解决了这个问题。你的答案似乎也正确。肯定会测试。我改用了 setInterval 。再次感谢! :)
    【解决方案2】:

    Javascript 不能保证您的超时和其他此类事件会准时触发。
    您应该使用 &gt;= 比较两个 Date 对象,并删除超时或您用于跟踪匹配 if 内时间的任何其他方法(然后在必要时重置它)。

    更多详情请见:https://stackoverflow.com/a/19252674/1470607
    或者,您可以使用字符串比较(但需要注意):https://stackoverflow.com/a/6212411/1470607

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多