简体   繁体   中英

Javascript how to start script on exact time

  1. script will start on exact time (ex: 2015:06:15:00:00)
  2. If its on time, it will alert HELLO every 1 second.

setInterval(function () {alert("Hello")}, 1000);

could you please help me how to make this on up?

There is no possibility to define a date driven trigger in javascript.

Instead you might register your function from the beginning and check there if the start date is reached.

<html>
    <head>
        <script type="text/javascript">
            var startDate = new Date("2015-06-14 12:47");
            window.setInterval(checkDate, 1000);

            function checkDate()
            {
                if (new Date() > startDate)
                    myDate.value = new Date().toLocaleString(); //or do your alert ;)
            }
        </script>
    </head>
    <body>
        <input type="text" id="myDate" style="width: 200px" />
    </body>
</html>
  1. I'd use the getTime object in JS
  2. I believe I have the time set right in this JSFiddle

    var d = new Date(); var year = d.getFullYear(); // Month 0 = January | Month 11 = December | so I changed vallues by +one var month = d.getMonth() + 1; var day = d.getDate(); var hour = d.getHours(); var minute = d.getMinutes(); var second = d.getSeconds(); var overall = year.toString() + month.toString() + day.toString() + hour.toString() + minute.toString() + second.toString(); alert(overall); var checkDate = function () { if(overall==="20156150000") { setInterval(function(){ alert("Hello"); }, 1000); }; }; window.setInterval(checkDate(), 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM