www.webdeveloper.com
Results 1 to 5 of 5

Thread: [RESOLVED] Run or schedule script/function to run one hour after provided time.

Hybrid View

  1. #1
    Join Date
    Nov 2013
    Posts
    41

    resolved [RESOLVED] Run or schedule script/function to run one hour after provided time.

    How can I schedule a function to run one hour after a specified time?
    Code:
    var custom_time = "2013-11-09T19:06:27-06:00";
    schedule(custom_time, 60, script());
    function script() {
      // Would run code here after 60 minutes
    }
    Of course, "schedule()" doesn't exist, I just put this here to show what I want to accomplish. I have MomentJs already in use on my site, and you can use it to manipulate the time if you need to. The provided time is in a ISO-8601 format (so it is compatible with MomentJs).

  2. #2
    Join Date
    Nov 2013
    Location
    London, United Kingdom
    Posts
    15
    You can use setTimeout function:

    Code:
    function script() {
      // Would run code here after 60 minutes
    }
    
    var custom_time = "2013-11-09T19:06:27-06:00";
    setTimeout(script, new Date().getTime() - Date.parse(custom_time) + 60 * 60 * 1000);

  3. #3
    Join Date
    Nov 2013
    Posts
    41
    I understand the code, but when I use just the math part:
    Code:
    new Date().getTime() - Date.parse(custom_time) + 60 * 60 * 1000
    and I input 2013-11-09T22:01:01-06:00, after formatting it it returns sumwhere around 7:30pm when accessing it at about 10:30pm. It should calculate that it needs to reload at 11:01pm. Which would be about 30 minutes.

  4. #4
    Join Date
    Nov 2013
    Location
    London, United Kingdom
    Posts
    15
    How do you format it? For me it returns different time because of the different timezone:

    Code:
    new Date(Date.parse('2013-11-09T22:01:01-06:00')).toString()
    // "Sun Nov 10 2013 04:01:01 GMT+0000 (GMT Standard Time)"

  5. #5
    Join Date
    Nov 2013
    Posts
    41
    I was formatting it using MomentJS.
    I just figured out that I can do this:
    Code:
    var custom_time = "2013-11-09T19:06:27-06:00";
    moment_now = moment(new Date());
    moment_customtime = moment(custom_time).add('h', 1);
    moment_runscripttime = moment_customtime.diff(moment_now);
    setTimeout(script, moment_runscripttime);
    It works! I think it's offset by 1 minute after, but I don't care about that. I could fix that if I wanted to. MomentJS is becoming more and more helpful.
    Last edited by DaAwesomeP; 11-10-2013 at 02:17 PM. Reason: typo!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles