Show / Hide ad by time at the same time worldwide

Viewed 110

The idea is like this: At 6:00 am Argentina, I want a announce (image) to be displayed that remains active for one hour, that is, that it can be visible and that when it reaches 60min it is hidden, that is , at 7:00 am hidden. That this action is repeated every 7 hours. Therefore I want it to remain hidden for 7 hours and repeat the action again. At 2:00 p.m. it appears and at 3:00 p.m. it hides. 7 hours pass. It reappears at 10pm and hides at 11pm. 7 hours pass and he appears again at 6:00 am.

I have this code created so that it recognizes the time differences and runs at the same time in all countries, that is, the ad comes out at 6:00 am Argentina and at the same time it is shown in Los Angeles even though it is 2:00 am. But it's not working. It appears at the time according to the country.

NOTE: there are two elements in the code, one is for another ad that appears at 0:00

var offset = new Date().getTimezoneOffset() / 60;
var horarios1 = [6 + offset, 14 + offset, 22 + offset];
var elemento1 = document.getElementById("panel1");
var horarios2 = [0 + offset];
var elemento2 = document.getElementById("panel2");
setInterval(function() {
 var hora = new Date().getHours();
 if (horarios1.includes((hora + offset) % 24)) {
   elemento1.style.display = 'block';
 } else {
   elemento1.style.display = 'none';
 }
 if (horarios2.includes((hora + offset) % 24)) {
   elemento2.style.display = 'block';
 } else {
   elemento2.style.display = 'none';
 }
}, 1000);
<div id="panel1" style="display: none;">PANEL 6, 14, 22</div>
<div id="panel2" style="display: none;">PANEL 0</div>

Thank you in advance.

1 Answers

Your code is using javascript time. Javascript takes the time from users machine. So when you visit your website, it will show your machine's time, when I visit it'll show my machine's time. However if you want a universal time for the whole world, i.e show the ad Argentina time 06:00 all over the world, than you can apply either of the following methods.

1. USE SERVER TIME

You need a bit of a backend code here. Show the time from your server, and its fixed for the whole world. Details depend on what backend technology (php/java/python) you are using.

2. USE A THIRD PARTY API

Use api from another website. Like worldtimeapi.org/. Make an ajax call, get the time of your desired location. You can use plain javascript or use any ajax library to do that. Here I'm including two methods: 1) plain javascript and 2) using axios (a popular ajax library)

Vanilla JS

function getTime(url) {
    return new Promise((resolve, reject) => {
        const req = new XMLHttpRequest();
        req.open("GET", url);
        req.onload = () =>
            req.status === 200
                ? resolve(req.response)
                : reject(Error(req.statusText));
        req.onerror = (e) => reject(Error(`Network Error: ${e}`));
        req.send();
    });
}

Now Use this function to make the ajax call

let url = "http://worldtimeapi.org/api/timezone/America/Argentina/Buenos_Aires";

getTime(url)
    .then((response) => { //the api will send this response which is a JSON
        // you must parse the JSON to get an object using JSON.parse() method
        let dateObj = JSON.parse(response);
        let dateTime = dateObj.datetime;
        console.log(dateObj);
        console.log(dateTime);
    })
    .catch((err) => {
        console.log(err);
    });

AXIOS

Add axios library to your project.

axios({
    url:"http://worldtimeapi.org/api/timezone/America/Argentina/Buenos_Aires",
    method: "get",
})
    // Here response is an object. The api will send you a JSON. But axios automatically
    // convert it to an object. So you don't need to convert it manually.
    .then((response) => {
        let dateObj = response.data;
        let dateTime = dateObj.datetime;
        console.log(dateObj);
        console.log(dateTime);
    })
    .catch((err) => {
        console.log(err);
    });

(function () {
 var url =
  "http://worldtimeapi.org/api/timezone/America/Argentina/Buenos_Aires",
  horarios1 = [6, 14, 22],
  elemento1 = document.getElementById("panel1"),
  horarios2 = [0],
  elemento2 = document.getElementById("panel2");

 function getTime(url) {
  return new Promise((resolve, reject) => {
   const req = new XMLHttpRequest();
   req.open("GET", url);
   req.onload = () =>
    req.status === 200
     ? resolve(req.response)
     : reject(Error(req.statusText));
   req.onerror = (e) => reject(Error(`Network Error: ${e}`));
   req.send();
  });
 }

 setInterval(function () {
  getTime(url)
   .then((data) => {
    var dateObj = JSON.parse(data);
    var dateTime = dateObj.datetime;
    var hora = Number(dateTime.slice(11, 13));

    if (horarios1.includes(hora)) {
     elemento1.style.display = "block";
    } else {
     elemento1.style.display = "none";
    }
    if (horarios2.includes(hora)) {
     elemento2.style.display = "block";
    } else {
     elemento2.style.display = "none";
    }
   })
   .catch((err) => {
    console.log(err);
   });
 }, 1000);
})();
  <div id="panel1" style="display: none;">PANEL 6, 14, 22</div>
  <div id="panel2" style="display: none;">PANEL 0</div>

Hope that helps. Few Things to remember though -

1. worldtimeapi.org/ is a third party service. If they choose to terminate their service, your code will break. But if you use your server time, as long as your server is running, your code will run.

2. Because of the ajax call, this code will not work in stackoverflow. Copy paste the code in your project to make it work.

3. If still it doesn't work, it means you are facing CORS (cross origin policy) issue. Read this link, search internet/SO. You will find your solution. Happy coding :)

Related