Working Out JavaScript Time with PHP Time - javascript

I am working on a page that pulls data from DB. PHP time() is captured and saved to the DB alongside user contents.
I want to be about to subtract the capturedTime from the current time using JavaScript and display how long the post has been made in hr : min : s and should be live.
HTML:
<div class = 'responses'>
<p class = 'capturedTime' style='display: none;'>123456789</p>
</div>
jQuery:
$(document).on('click', '.responses', function () {
$this = $( this );
timeC = $this.prev('.capturedTime').text();
timeNow = $.now()
timeLapsed = ( timeNow - timeC )/1000;
seconds = timeLapsed/60;
mins = seconds/60;
hrs = mins/24;
if ( timeLapsed !== NaN ){
alert(seconds + '------' + mins + '---' + hrs);
}
});

I suggest you to change your code this way:
Fiddle
<body>
<div class='responses'>
<p class='capturedTime' data="1401270715145"></p>
</div>
</body>
var $times, timer;
$times = $('.capturedTime');
timer = setInterval(function () {
var i, len, cache, value, now, minutes, seconds;
for (i = 0, len = $times.length; i < len; i = i + 1) {
cache = $times.eq(i);
now = new Date().getTime();
value = new Date(now - parseInt(cache.attr("data")));
minutes = value.getMinutes();
seconds = value.getSeconds();
cache.html("m:" + minutes + " ss:" + seconds);
}
}, 1000);

try this :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://timeago.yarp.com/jquery.timeago.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var lastUpdate = new Date($(".capturedTime").html()*1000)
alert($.timeago(lastUpdate));
});
</script>
or visit this page

Related

My JS timer clock is not stopping when clicked twice on start button [duplicate]

This question already has an answer here:
JavaScript countdown timer with on key press to reset the timer
(1 answer)
Closed 11 months ago.
I have a simple HTML stopwatch logic where I can start and stop the clock with the button click. By clicking on the start button, one can start the timer (shows current time) and update every second. One can stop it by clicking stop button. But if one clicks on start button twice, there is nothing I can do to stop the timer. Below is my code:
var hour = document.getElementById("hoursOut");
var minute = document.getElementById("minsOut");
var second = document.getElementById("secsOut");
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
var waitTimer;
function displayTime() {
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
hour.innerHTML = twoDigit(currentHour) + ":";
minute.innerHTML = twoDigit(currentMinute) + ":";
second.innerHTML = twoDigit(currentSeconds);
}
function twoDigit(digit) {
if (digit < 10) {
digit = "0" + digit;
}
return digit;
}
function startClock() {
waitTimer = setInterval(displayTime, 1000);
}
function stopClock() {
clearInterval(waitTimer);
}
btnStart.onclick = startClock;
btnStop.onclick = stopClock;
<h1>JavaScript Clock</h1>
<div id="calendarBox">
<!-- OUTPUT TIME VALUES -->
<p class="timeDisplay">
<span id="hoursOut">00:</span>
<span id="minsOut">00:</span>
<span id="secsOut">00</span>
</p>
<!-- BUTTON SET -->
<input id="btnStart" type="button" value="START" />
<input id="btnStop" type="button" value="STOP" />
</div>
I have checked some answers in stackoverflow but most solutions uses a for-loop from 0 to 1000 until it finds the interval id and stop all of them using loop. I am confident there should be an elegant solution than that.
// some stackoverflow suggested answer
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
A possible solution is to prevent the problem before it happens. You can place a check on the running timer (Is there a way to check if a var is using setInterval()?).
In this case you could just have a global timer variable var timer = false the with add a check to the start function. Then the stop function will set the timer variable back to false.
function startClock() {
if(!timer){
timer = true
waitTimer = setInterval(displayTime, 1000);
}
else return
}
function stopClock() {
clearInterval(waitTimer);
timer = false
}
when you double click you start a new setInterval(). So you now have two set intervals running. Only problem is you can't access the first one cause you named the second one the same name. Check if waitTimer exists and if it does stop it. see code:
UPDATE: actually you don't even need an if statement. just call stopClock() before you set waitTimer -- code snippet adjusted
var hour = document.getElementById("hoursOut");
var minute = document.getElementById("minsOut");
var second = document.getElementById("secsOut");
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
var waitTimer;
function displayTime() {
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
hour.innerHTML = twoDigit(currentHour) + ":";
minute.innerHTML = twoDigit(currentMinute) + ":";
second.innerHTML = twoDigit(currentSeconds);
}
function twoDigit(digit) {
if (digit < 10) {
digit = "0" + digit;
}
return digit;
}
function startClock() {
stopClock();
waitTimer = setInterval(displayTime, 1000);
}
function stopClock() {
clearInterval(waitTimer);
}
btnStart.onclick = startClock;
btnStop.onclick = stopClock;
<h1>JavaScript Clock</h1>
<div id="calendarBox">
<!-- OUTPUT TIME VALUES -->
<p class="timeDisplay">
<span id="hoursOut">00:</span>
<span id="minsOut">00:</span>
<span id="secsOut">00</span>
</p>
<!-- BUTTON SET -->
<input id="btnStart" type="button" value="START" />
<input id="btnStop" type="button" value="STOP" />
</div>

Chrome Extension: calculate in miliseconds and click button after specific seconds

Well i am practising on Chrome Extension , i'm newbie on this.
Here is my code.
popup.html
<!doctype html>
<html>
<head>
<title>Laser Script</title>
<script type="text/javascript" src="popup.js"></script>
<style type="text/css">
h1 { font-size: 22px; }
.powered {
font-size: 14px;
margin-top: 8px;
}
</style>
</head>
<body>
<h1>Scheduled Click</h1>
<div id="contentWrapper">
<input type="text" id="duration" placeholder="Duration">
<input type="text" id="attack_date" placeholder="Day/Month/Year">
<input type="text" id="attack_time" placeholder="00:00:00">
<button id="schedule">Start Attack</button>
</div>
<div class="powered">Courtesy of <img src="justpark_logo.png" width="170px"></div>
</body>
</html>
popup.js
function initialise () {
// here im calculating the remind time in (mileseconds) that the button have to be pressed
var attack_timeInput = document.getElementById("attack_time");
var attack_timeParts = attack_timeInput.value.split(":");
var hours = parseInt(attack_timeParts[0],10);
var minutes = parseInt(attack_timeParts[1],10);
var seconds = parseInt(attack_timeParts[2],10);
var mileseconds = parseInt(attack_timeParts[3],10);
var attack_DateInput = document.getElementById("attack_date");
var attack_DateInputParts = attack_DateInput.value.split("/");
var day = parseInt(attack_DateInputParts[0],10);
var month = parseInt(attack_DateInputParts[1],10);
var year = parseInt(attack_DateInputParts[2],10);
var durationInput = document.getElementById("duration");
var durationParts = durationInput.value.split(":");
var hours2 = parseInt(durationParts[0],10)*3600000;
var minutes2 = parseInt(durationParts[1],10)*60000;
var seconds2 = parseInt(durationParts[2],10)*1000;
var duration_mile = hours2+minutes2+seconds2;
var now = new Date();
var new_now = now.getTime();
var full_attack_date = new Date(year, month-1, day, hours, minutes, seconds, mileseconds);
var new_full_attack_date = full_attack_date.getTime();
var delayInputValue = new_full_attack_date - new_now - duration_mile;
function scheduleClick () {
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
var codeString = 'var button = document.getElementById("troop_confirm_go"); setTimeout( function() { button.click(); },' + delayInputValue + ' )';
console.log(codeString);
chrome.tabs.executeScript({ code: 'console.log(document.getElementById("The attack will start ' + delayInputValue + ' miliseconds"))' });
chrome.tabs.executeScript({ code: codeString});
};
scheduleButton = document.getElementById("schedule");
scheduleButton.addEventListener('click', scheduleClick, true);
};
document.addEventListener('DOMContentLoaded', initialise, false);
So i have 3 inputs. I calculate the remind time until the button will be clicked. (it works)
But in this part
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
it diplays
The attack will start in NaN miliseconds.
and the button is pressed instantly.
I ckeched also this code:
var p = 1 ; //it's outside the function as the var delayInputValue
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'seconds';
and it displays :
The attack will start in 1 miliseconds.
So here is my question, why it can't read and work with the var delayInputValue but i can the var p?
Can i fix it somehow ?
Got it - the initialise() function is called when your DOM content is finished loading. At that point, the user has not entered information into the text fields, so they show as null or undefined. When the code starts running with this data it produces data as NaN since the calculations don't work.
In order for the code to run properly, you need to place the code dealing with data from those fields inside the scheduleClick() function, like so:
function initialise () {
function scheduleClick () {
var attack_timeInput = document.getElementById("attack_time");
var attack_timeParts = attack_timeInput.value.split(":");
var hours = parseInt(attack_timeParts[0],10);
var minutes = parseInt(attack_timeParts[1],10);
var seconds = parseInt(attack_timeParts[2],10);
//var mileseconds = parseInt(attack_timeParts[3],10);
var attack_DateInput = document.getElementById("attack_date");
var attack_DateInputParts = attack_DateInput.value.split("/");
var day = parseInt(attack_DateInputParts[0],10);
var month = parseInt(attack_DateInputParts[1],10);
var year = parseInt(attack_DateInputParts[2],10);
var durationInput = document.getElementById("duration");
var durationParts = durationInput.value.split(":");
var hours2 = parseInt(durationParts[0],10)*3600000;
var minutes2 = parseInt(durationParts[1],10)*60000;
var seconds2 = parseInt(durationParts[2],10)*1000;
var duration_mile = hours2+minutes2+seconds2;
var now = new Date();
var new_now = now.getTime();
var full_attack_date = new Date(year, month-1, day, hours, minutes, seconds);
var new_full_attack_date = full_attack_date.getTime();
var delayInputValue = new_full_attack_date - new_now - duration_mile;
document.getElementsByTagName("div")[0].innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
};
scheduleButton = document.getElementById("schedule");
scheduleButton.addEventListener('click', scheduleClick, true);
};
document.addEventListener('DOMContentLoaded', initialise, false);
Note that I also removed the miliseconds variable as the inputs I was using included hours, minutes and seconds only. You should also add some code to sanitise inputs to make sure they are in the format you want before calling the function.
Hope that helps

How to display timestamp on a website and terminate a session after a particular time?

So I have this code which displays the current timestamp(IST)
<?php echo date("D M d, Y "); ?> </b>
<body onload="digiclock()">
<div id="txt"></div>
<script>
function digiclock()
{
var d=new Date();
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
if(s==60)
{
s=0;
m+=1;
}
if(m==60)
{
m=0;
h+=1;
}
if(h==12)
{
h=0;
}
var t=h>=12?'PM':'AM';
document.getElementById('txt').innerHTML=h+":"+m+":"+s+" "+t;
var t=setTimeout(digiclock,500);
}
How to compress this code and how to use it calculate a time limit for terminate a session. For example, a person is playing quiz and the quiz should terminate after 5 minutes and generate the score based on the questions attempted.
Here is example how to use #rckrd's js code snippet with PHP script called by AJAX.
The example is very basic, just to demonstrate implementation logic.
You cann look for live demo here http://demo1.rrsoft.cz/
Download code here http://demo1.rrsoft.cz/test.zip
index.php with HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="startQuiz()">Start timer</button>
<div id="messages"></div>
<div id="timerView"></div>
<div id="quiz_body"></div>
<script src="ajax.js"></script>
</body>
</html>
ajax.js with needed functions (I used #rckrd snippet, because is a grat example how to use it with PHP)
// This function has call php script with quiz answer...
var doAnswer = function(number){
var response_value = $('[name="qr'+number+'"]').val();
var response_message = '"Quiz #' + number + ' has successfuly saved';
$('[name="qr'+number+'"]').prop( "disabled", true );
$.ajax({
url: '/answer.php',
type: 'POST',
async: true,
data: {
quiz: number,
value: response_value
},
success:function(response){
if(response === 'OK'){
$('#messages').html(response_message);
}
},
error: function(xhr, type, exception) {
var _msg = "Service through error: ("+xhr.status+") " + exception.toString();
var _err = $('#messages');
_err.text(_msg).show();
}
});
}
// This function just call the php script to render all quiz questions...
var startQuiz = function(){
$.ajax({
url: '/quiz.php',
type: 'GET',
async: true,
data: {
started: true
},
success:function(response){
$('#quiz_body').html(response);
startTimer();
},
error: function(xhr, type, exception) {
var _msg = "Service through error: ("+xhr.status+") " + exception.toString();
var _err = $('#messages');
_err.text(_msg).show();
}
});
}
// Arange elements over time limit
var gameOver = function(){
$('#header').html('Game over');
$('#list').hide();
}
// This function manage time limitation logic and is called when quiz has started...
var startTimer = function (){
var timeLeftInMillis = 1*60*1000;
var startTime = new Date().getTime();
var updateTimeInMillis = 25;
var intervalId = setInterval(function(){
var now = new Date().getTime();
var diffInMills = now - startTime;
startTime = new Date().getTime();
timeLeftInMillis = timeLeftInMillis - diffInMills;
var oneSecondInMillis = 1000;
if(timeLeftInMillis < oneSecondInMillis){
clearInterval(intervalId);
gameOver();
return;
}
var seconds = Math.floor((timeLeftInMillis / 1000) % 60) ;
var minutes = Math.floor((timeLeftInMillis / (1000*60)) % 60);
document.getElementById("timerView").innerHTML = minutes + ' min, ' +seconds+' sec remaining';
},updateTimeInMillis);
};
The quiz.php called by AJAX:
<?php
// very easy list of quizes...
$quiz_template = '
<h1 id="header">Quiz started!</h1>
<ul id="list">
<li>
Quiz 1 text
<input type="text" name="qr1" size="5"/>
<button id="bt1" onclick="doAnswer(1)">Send answer</button>
</li>
<li>
Quiz 2 text
<input type="text" name="qr2" size="5"/>
<button id="bt2" onclick="doAnswer(2)">Send answer</button>
</li>
<li>
Quiz 3 text
<input type="text" name="qr3" size="5"/>
<button id="bt3" onclick="doAnswer(3)">Send answer</button>
</li>
<li>
Quiz 4 text
<input type="text" name="qr4" size="5"/>
<button id="bt4" onclick="doAnswer(4)">Send answer</button>
</li>
<li>
Quiz 5 text
<input type="text" name="qr5" size="5"/>
<button id="bt5" onclick="doAnswer(5)">Send answer</button>
</li>
</ul>
';
// ... and return it
if((bool) $_GET['started'] === true){
die($quiz_template);
}
And Finaly answer.php
<?php
if($_POST){
// grab all needed posted variables... THIS IS JUST FOR DEMO, BECAUSE IS UNSECURED
$quizNumber = $_POST['quiz'];
$quirAnswer = $_POST['value'];
// do quiz PHP logic here, save answer to DB etc...
// when php script runs without errors, just return OK
$error = false;
if($error === false){
die('OK');
}else{
die($someErrorMessage);
}
}
var gameOver = function(){
document.getElementById("timerView").innerHTML = 'Game over';
}
var startTimer = function (){
var timeLeftInMillis = 5*60*1000;
var startTime = new Date().getTime();
var updateTimeInMillis = 25;
var intervalId = setInterval(function(){
var now = new Date().getTime();
var diffInMills = now - startTime;
startTime = new Date().getTime();
timeLeftInMillis = timeLeftInMillis - diffInMills;
var oneSecondInMillis = 1000;
if(timeLeftInMillis < oneSecondInMillis){
clearInterval(intervalId);
gameOver();
return;
}
var seconds = Math.floor((timeLeftInMillis / 1000) % 60) ;
var minutes = Math.floor((timeLeftInMillis / (1000*60)) % 60);
document.getElementById("timerView").innerHTML = minutes + ' min, ' +seconds+' sec remaining';
},updateTimeInMillis);
};
<button onclick="startTimer()">Start timer</button>
<div id="timerView"></div>
If you are open to use third part libraries then check out EasyTimer.js plugin, this will solve the issue.
https://albert-gonzalez.github.io/easytimer.js/
or
countdownjs: http://countdownjs.org/demo.html
This is impossible in php, the best way is use JavaScript/Ajax...

multiple alarm clock in javascript using dynamic generated input elements in javascript

I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>

JS is refusing to loop a function [duplicate]

This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 7 years ago.
I am having a problem with a countdown. I have made the countdown however the JS to change the HTML refuses to loop. I have a setInterval and I have tried for, while and do loops but none work. I would really appreciate some help.
HTML:
<body>
<center>
<h1> Input the date and time you want to countdown to!</h1>
<form>
Second:<input id="seconds" type="number"><br>
Minute:<input id="minutes" type="number"><br>
Hour:<input id="hours" type="number"><br>
Day:<input id="days" type="number"><br>
Month:<input id="months" type="text"><br>
Year:<input id="years" type="number"><br>
</form>
<button onclick="start()">Calculate!</button>
<h1 id="yearsres"></h1>Years<br>
<h1 id="monthsres"></h1>Months<br>
<h1 id="daysres"></h1>Days<br>
<h1 id="hoursres"></h1>Hours<br>
<h1 id="minutesres"></h1>Minutes<br>
<h1 id="secondsres"></h1>Seconds<br>
</center>
</body>
JS:
function start() {
var myVar = setInterval(test(), 1000)
}
function test() {
console.log("hi");
}
function calculateseconds(sec) {
var year = document.getElementById("years").value;
var month = document.getElementById("months").value;
var day = document.getElementById("days").value;
var hour = document.getElementById("hours").value;
var minute = document.getElementById("minutes").value;
var second = document.getElementById("seconds").value;
var countdownto = new Date(month + " " + day + "," + " " + year + " " + hour + ":" + minute + ":" + second);
var epochto = countdownto.getTime()/1000.0;
var current = new Date();
var epochcurrent = current.getTime()/1000.0;
var epochcountdown = epochto - epochcurrent;
var t = parseInt(epochcountdown);
var years = 0;
var months = 0;
var days = 0;
var i = 1;
if(t>31556926){
years = parseInt(t/31556926); t = t-(years*31556926);
}
if(t>2629743){
months = parseInt(t/2629743); t = t-(months*2629743);
}
if(t>86400){
days = parseInt(t/86400); t = t-(days*86400);
}
var hours = parseInt(t/3600);
t = t-(hours*3600);
var minutes = parseInt(t/60);
t = t-(minutes*60);
document.getElementById("yearsres").innerHTML = years;
document.getElementById("monthsres").innerHTML = months;
document.getElementById("daysres").innerHTML = days;
document.getElementById("hoursres").innerHTML = hours;
document.getElementById("minutesres").innerHTML = minutes;
document.getElementById("secondsres").innerHTML = t;
}
By adding () to your test function you call it. setInterval method takes a reference to the function (name of the function) and interval in milliseconds.
It can be used like this:
function start() {
var myVar = setInterval(test, 1000);
}
Or like this:
function start() {
var myVar = setInterval(function() {
test();
}, 1000);
}
Also if you need to pass parameters to your function you can do it like this:
function start() {
var myVar = setInterval(test, 1000, "First param", "Second param");
}
Remove () from test()
somehow it will work
https://jsfiddle.net/alesmana/u30zmj3t/

Categories

Resources