开发者

insert an element at a certain time of the day

开发者 https://www.devze.com 2023-01-09 06:20 出处:网络
what is the best way to do something , like inserting an ele开发者_运维百科ment at a certain time of the day ? should I use setTimeout() os is there a better way to do it ?First, decide whether this i

what is the best way to do something , like inserting an ele开发者_运维百科ment at a certain time of the day ? should I use setTimeout() os is there a better way to do it ?


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.


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.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号