How to run javascript function at specified time

I want to run a specific javascript function

date / time only once. For example, I have a date time variable in php

as shown below.

  $date = "May 7, 2015 17:08:43";

      

I have some function like

 function some_function()
 {
   .....
   .....
 } 

      

How can I run this function only once at the specified time May 7, 2015 17:08:43

.

I tried this but it doesn't work correctly.

var date = "<?php echo date('n/j/Y/H:i', strtotime($date));?>";
var myDate = new Date();
var current_date =  (myDate.getMonth()+1)  + "/" + myDate.getDate() + "/" + myDate.getFullYear()+ "/"+ myDate.getHours() + ":" + myDate.getMinutes();
var interval = setInterval(function() { 
    if(date==current_date)
    {
       some_function();           

    }

}, 4000);
clearInterval(interval);

      

Is there a good technique for doing this?

+3


source to share


6 answers


I think you can do the following:

setInterval(function() {
    var myDate = new Date();
    $date = "May 06 2015 13:50:40";
    var reg = new RegExp('\(' + $date.replace(/\s/g, "\\s") + '\)', 'g');
    console.log(myDate)
    if ( myDate.toString().match($date) ) {
        do_something();
    }
}, 1000);

      



here's a demo: http://jsfiddle.net/pj1248xq/

Note : you need to change the date according to the actual date you want to executefunction

+1


source


Calculate number of seconds server side
usesetTimeout(function(){ some_function(); }, nbreOfSeconds);



setInterval()

will evaluate your expression at specific intervals

+1


source


You can use this javascript method. convert your time to milliseconds.

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

      

+1


source


You should use setTimeout instead of setInterval as @Halayem said because setTimeout will be executed after after

where setInterval will execute and then wait for period (nbreOfSeconds) then loops again

ok, you can make an ajax call with JQuery (simple option) and in your server side language check the date and then return the json state object like

here is a simple example:

check_date.php (this file is used to check the date):

<?php
   $date = date('n/j/Y/H:i', strtotime($date));
   if($date == 'your wanted date'){
      return json_encode(array('status'=>1));
   }else{
      return json_encode(array('status'=>0));
   }
?>

      

and this is your JavaScript code: of course you must load jquery first

//here is a jquery cdn link : 
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> 
<script>
$(document).ready(function(){
    $.('check_date.php',{},function(serverRespond){
       jsonRespond = JSON.parse(serverRespond);
       if(jsonRespond.status === 1){
          setTimeout(function(){
            // here is your js function that you want to execute 
          },afterMilSeconds);

       }
    });
});
</script>

      

+1


source


function runAt (cbk, timestamp) {
    if (
        ! (timestamp instanceof Date)
        || isNaN (timestamp.getTime())
    ) throw "timestamp should be a valid Date object";
    var ms = timestamp - (new Date()).getTime();
    if (ms < 0) throw "Too late!!";
    setTimeout(cbk, ms);
};

      

You can check it "anytime" with

runAt(function(){console.log("Hello!!");}, new Date(new Date().getTime() + 5000));

      

+1


source


There's a small library useful for this on github

The native setTimeout functions are capped at INT32 (2147483647 milliseconds or roughly 24.8 days). This library allows you to set timeouts with almost unlimited latency.

After you have included the library, you can set the timeout like this:

// extra zeros need to get the time in milliseconds (as in JavaScript)
var date = <?php echo strtotime($date);?>000;
var id = timeout.set(some_function, date);

function some_function()
{
    // do some cool stuff
    timeout.clear(id);
}

      

+1


source







All Articles