Skip to content Skip to sidebar Skip to footer

Insert An Element At A Certain Time Of The Day

what is the best way to do something , like inserting an element at a certain time of the day ? should I use setTimeout() os is there a better way to do it ?

Solution 1:

First, decide whether this is something that needs to happen on the client or server side. You haven't provided enough info to determine that but since you've tagged this Javascript I assume client-side is the best way.

Going with that assumption it sounds like the user will have an open web page and at certain times of the day you want to manipulate or add content.

Here is an example:

Check every minute, and show a DIV (with an ID of target) with pre-existing content only when it is after 1:59pm and before 6:00pm (on the users timezone):

setTimeout ( function(){

  var hour = (new Date()).getHours();
  if (hour>1 && <6) {
    document.getElementById('target').style.display = "block";
  } else {
    document.getElementById('target').style.display = "none";
  }

}, 60000 );

You could of course change it to use createElement to insert a new DIV, and to also make an AJAX request to get the content etc but thats up to you.

Solution 2:

setInterval() is better for that. But don't set the interval for 24 hrs, or whatever. Set it to check the time every minute or so, and if the new Date() is greater than the time of day you want, then run your element insertion function.

Solution 3:

setTimeout() and setInterval() both execute timed js statements in relation to when they were loaded, not at a specific time each day, so they don't seem like a clean solution. You could throw a bit of server-side scripting in there. Some random solutions plucked from my tired brain:

  • Simply wrap the html element in a conditional statement (php, python, etc) that only executes at a given time
  • Have the element on the page but set it to display:none. Use php to add a class / style at a certain time that overrides the display attribute.
  • Again, use php to add a class, but this time add the element into the DOM with js, using the new class as the identifier for the new element's location.

Obviously not great if you want to keep everything client-side... :)

EDIT To execute a statement in php between 1pm and 2pm every day (untested):

$now = date('G',time());
$start = 13;
$end = 14;
if($now >= $start && $now <= $end){ 
    //do something
}

Post a Comment for "Insert An Element At A Certain Time Of The Day"