I would like to display an element only within a certain period of time. I would like to solve this with the milliseconds.
I have already researched but did not find an exact answer to my question. Especially not with my idea of the implementation.
My current code is the following. What is wrong with it?
var begin = 1585684800000; // Dienstag, 30.03.2020, 22:00 Uhr
var end = 1585720800000; // Mittwoch, 01.04.2020, 08:00 Uhr
var now = new Date().getTime();
//console.log(now);
if (now >= begin && now <= end) { // zwischen Dienstag, 30.03.2020, 21:59 Uhr und Mittwoch, 01.04.2020, 07:59 Uhr
$(".box").hide();
}
The code you provided works, but only runs one time. What I mean is that you are missing to loop every millisecond if the element must be visible or not.
In Javascript you have the setInterval built-in function to acomplish what you want. In order to check if "now" is between two dates in milliseconds, you need to set an interval this way:
var started = Date.now();
var begin = 1585684800000;
var end = 1585720800000;
var current_time = document.getElementById("current_time");
var result = document.getElementById("result");
var counter = setInterval(function(){
var now = Date.now();
current_time.innerHTML = now;
if(now >= begin && now <= end)
{
result.innerHTML = 'visible';
} else {
result.innerHTML = 'not visible';
}
}, 100);
<span id="current_time"></span>
<span id="result"></span>
As you can see un my working example... the tag with current_time id will show the current timestamp live.
I hope the code help you to understand the setInterval concept.