In JavaScript, how can I have a function run at a specific time?

前端 未结 5 1218
感动是毒
感动是毒 2020-12-03 00:05

I have a website that hosts a dashboard: I can edit the JavaScript on the page and I currently have it refreshing every five seconds.

I am trying to now get a

5条回答
  •  甜味超标
    2020-12-03 00:19

    I will suggest to do it in Web Worker concept, because it is independent of other scripts and runs without affecting the performance of the page.

    1. Create a web worker (demo_worker.js)

      var i = 0;
      var date = new Date();
      var counter = 10;
      var myFunction = function(){
          i = i + 1;
          clearInterval(interval);
          if(date.getHours() === 8 && date.getMinutes() === 0) {
              counter = 26280000;
              postMessage("hello"+i);
          }    
          interval = setInterval(myFunction, counter);
      }
      var interval = setInterval(myFunction, counter);
      
    2. Use the web worker in Ur code as follows.

      var w;    
      function startWorker() {
          if (typeof(Worker) !== "undefined") {
              if (typeof(w) == "undefined") {
                  w = new Worker("demo_worker.js");
                  w.onmessage = function(event) {
                      window.print();
                  };
              } else {
                  document.getElementById("result").innerHTML = "Sorry, your browser does not support HTML5 Web Workers";
              }
          }
      }
      

    I think it will help you.

提交回复
热议问题