Call a javascript function at a specific time of day

前端 未结 3 1021
时光取名叫无心
时光取名叫无心 2020-11-22 16:22

for example i want to call a js function at 10.00.00.00 am how can i do?



        
相关标签:
3条回答
  • 2020-11-22 17:05

    You'll need setTimeout to set a timer and Date to calculate how long the timer needs to go until it triggers.

    var now = new Date();
    var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
    if (millisTill10 < 0) {
         millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
    }
    setTimeout(function(){alert("It's 10am!")}, millisTill10);
    
    0 讨论(0)
  • 2020-11-22 17:07

    Assuming the code is located on a web page that will be loaded before 10:00 and will still be viewed at 10:00, you can use setTimeout() to set up a timed event. the function takes some JS statement to execute, and the number of milliseconds before it should execute. You can find this second part pretty easily with the built-in date functions.

    0 讨论(0)
  • 2020-11-22 17:14

    My solution for running a script at a specific time, btw no error checking for negative timeout.

    //year, month 0-11, date, hour, min (can add ,sec,msec)
    var eta_ms = new Date(2015, 0, 21, 17, 0).getTime() - Date.now();
    var timeout = setTimeout(function(){}, eta_ms);
    
    0 讨论(0)
提交回复
热议问题