Timer not accurate [duplicate] - javascript

This question already has answers here:
How to create an accurate timer in javascript?
(15 answers)
Closed 6 years ago.
I am building an activity timer, but the code I have is not working properly. The timer is going ~40% faster than real time. What's going wrong?
var sec = 00;
var min = 00;
var hr = 00;
var t;
var timer_is_on = 0;
function timedCount() {
if (min == 0) {
min = 1;
}
document.getElementById('seconds').value = sec;
document.getElementById('minutes').value = min;
$('.node-form .form-item:nth-child(4) input').val(min);
document.getElementById('hours').value = hr;
$('.node-form .form-item:nth-child(3) input').val(hr);
sec = sec + 1;
if (sec == 60) {
sec = 0;
min = min + 1;
if (min == 60) {
min = 1;
hr = hr + 1;
}
}
t = setTimeout("timedCount()", 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetCount() {
stopCount();
sec = 0;
min = 0;
hr = 0;
document.getElementById('hours').value = 00;
$('.node-form .form-item:nth-child(3) input').val('0');
document.getElementById('minutes').value = 00;
$('.node-form .form-item:nth-child(4) input').val('0');
document.getElementById('seconds').value = 00;
}
function putInTimelog() {
// Put hours
var hourItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-hours-0-value-", 0) === 0) {
hourItems.push(hourFields[i]);
}
}
var hourField = 'edit-field-timelog-hours-0-value-';
hourField = hourField.concat(hourItems.length);
document.getElementById(hourField).value = hr;
// Put minutes
var minuteItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-minutes-0-value-", 0) === 0) {
minuteItems.push(hourFields[i]);
}
}
var minuteField = 'edit-field-timelog-minutes-0-value-';
minuteField = minuteField.concat(minuteItems.length);
alert(minuteField);
alert((minuteField).length);
document.getElementById(minuteField).value = min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span class="timer-title"><strong>Activity timer</strong></span>h:
<input id="hours" readonly="readonly" size="2" type="text" /> m:
<input id="minutes" readonly="readonly" size="2" type="text" /> s:
<input id="seconds" readonly="readonly" size="2" type="text" /><span class="timer-buttons"><input onclick="doTimer()" type="button" value="Start" /> <input onclick="stopCount()" type="button" value="Stop" /> <input onclick="resetCount()" type="button" value="Reset" /> </span>
</form>
View on JSFiddle

clock.js is my repo that might help when used in conjunction with window.setInterval(). Working example included.
Add <script src="https://rack.pub/clock.min.js"></script> to your HTML then call clock.now --> 1462248501241 each time you want a time snapshot. You can add and subtract intuitively from there.
The actual js looks like:
var clock = (function() {
// object to expose as public properties and methods such as clock.now
var pub = {};
//clock.now
Object.defineProperty(pub, "now", {
get: function () {
return Date.now();
}
});
//API
return pub;
}());
var doc = document;
var el = doc.getElementById('output');
window.setInterval(function(){
/// call your function here
el.innerHTML = clock.what.time(clock.now);
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rack.pub/clock.min.js"></script>
<h2 id='output'></h2>

Related

Why am I getting 1 number short of my inputted number e.g 10 outputs 9

Building a countdown Timer with rounds, working and resting for training.
Issue: My timer seems to start fine (with the user inputted values) after the first round, once rest is done, my working timer doesn't start at the inputted value like it should. It's always one number short.
E.g If you input 5: 10: 10. When it comes back around, it will appear one number shorter than it should 4: 09: 00
From the left the Timer is rounds, working, rest.
Please help.
let rnd = '00';
let wrk = 00; // this will act as my seconds
let rst = '00';
let prepare =3;
let interval;
let rstInterval;
let startTimer = '00';
// store the working set in an array
let prepIn = document.getElementById('prep');
prepIn.innerHTML = prepare;
// buttons
document.getElementById('start').addEventListener('click', initTimer);
document.getElementById('pause').addEventListener('click', pauseTimer);
document.getElementById('reset').addEventListener('click', finishTimer);
let span= document.getElementById('app').getElementsByTagName('span');
function initTimer(){
clearInterval(interval)
let rounds = document.querySelector('.rounds').value;
rnd = rounds;
span[0].innerHTML = rnd
let work = document.querySelector('.work').value;
wrk = work;
startTimer = work;
span[1].innerHTML =wrk
let rest = document.querySelector('.rest').value;
rst = rest;
span[2].innerHTML = rst
console.log(startTimer)
interval= setInterval(countDown, 1000);
}
// Pause the timer
function pauseTimer(){
clearInterval(interval);
console.log("pauseTimer")
}
// reset timer
function finishTimer(){
clearInterval(interval);
span[0].innerHTML = '00'
span[1].innerHTML = '00'
span[2].innerHTML = '00'
rnd = '00';
wrk = '00';
rst = '00';
document.querySelector('.timeNum').style.display = "flex"
}
function countDown(){
prepare--
if(prepare < 10){
prepIn.innerHTML = '0' + prepare;
}
if(prepare >=9){
prepIn.innerHTML = prepare;
}
if(prepare <= 3){
prepIn.style.color = 'green';
}
if(prepare < 1){
clearInterval(interval)
prepare = 00
prepIn.style.display = 'none'
clearInterval(startTimer)
startTimer= setInterval(timerActive, 1000);
let work = document.querySelector('.work').value;
wrk = work;
console.log(wrk)
}
document.querySelector('.timeNum').style.display = "none";
}
function timerActive(){
wrk--
if(wrk <=9){
span[1].innerHTML = '0' + wrk;
}
if(wrk >=10){
span[1].innerHTML = wrk;
}
if(wrk <= 0){
clearInterval(startTimer)
let rest = document.querySelector('.rest').value;
rst = rest
let rstInterval = setInterval(() => {
rst--
if(rst<=9){
span[2].innerHTML = '0' + rst;
}
if(rst >=10){
span[2].innerHTML = rst;
}
if(rst < 1){
clearInterval(rstInterval)
rstcount();
}
},1000)
rnd--
if(rnd <10){
span[0].innerHTML = '0'+ rnd;
}
else{
span[0].innerHTML = rnd;
}
}
};
function rstcount(){
clearInterval(rstInterval);
countDown();
}
<div class="timer">
<div class="numb">
<h2 id="prep"></h2>
<h2 id="app"><span>00</span>:<span>00</span>:<span>00</span></h2>
<h1 class="timeNum"><input type='number' min="00" max="99" class="rounds" value='00'>:<input type='number' min="00" max="99" class="work" value="00">:<input type='number' min="00" max="99" class="rest" value="00"></h1>
<div class="buttons">
<input type="button" id="start" value="Start">
<input type="button" id="pause" value="Pause">
<input type="button" id="reset" value="Reset">
</div>
</div>
</div>

Web page displays and animated times table

Hi everyone I am currently stuck trying to debug my program. MY goal is for whenever the button "Start Animation" is clicked, the web page displays an animated times table according to the number that the user enters in the text field in the following manner. For example, if the user entered the number 6 in the text field, then the animation displays 1 x 6 = 6, one second later it replaces it with 2 x 6 = 12, one second later it replaces it with 3 x 6 = 18, etc. If it is 9 x 6 = 54, then one second later it becomes 1 x 6 = 6, and then 2 x 6 = 12, and so on.
var counter;
var animationOn = false;
var counterAnimation;
function updateAnimation() {
var value = document.getElementById('value1').value;
for (var i = 1; i < 1000; i++) {
for (var j = 1; j < 10; j++) {
var product = j * value;
var counterSpan = document.getElementById("counterHolder");
counterSpan.innerHTML = product;
}
}
counterAnimation = setTimeout(updateAnimation, 1000);
}
function startAnimation() {
if (animationOn == false) {
animationOn = true;
counter = 1;
counterAnimation = setTimeout(updateAnimation, 1000);
}
}
function stopAnimation() {
if (animationOn == true) {
animationOn = false;
clearTimeout(updateAnimation);
}
}
<body>
<button onclick="startAnimation();">
Start animation
</button>
<button onclick="stopAnimation();">
Stop animation
</button><br><br>
<label>Enter an integer: </label>
<input type="number" size=20 id=value1 name="value">
<span id="counterHolder">0</span>
</body>
Edited
Here is a complete solution which makes changes displayed value by time
let counter;
let animationOn = false;
let counterAnimation;
let mult = 1;
function updateAnimation() {
let value = document.getElementById('value1').value;
let counterSpan = document.getElementById("counterHolder");
if (mult >= 10) {
mult = 1;
counter = null;
animationOn = false;
counterAnimation = null;
counterSpan.innerHTML = 0;
return;
}
let product = mult * value;
counterSpan.innerHTML = product;
mult++
counterAnimation = setTimeout(updateAnimation, 1000)
}
function startAnimation() {
if (!animationOn)
{
animationOn = true;
counter = 1;
counterAnimation = setTimeout(updateAnimation, 1000);
}
}
function stopAnimation() {
if (animationOn)
{
animationOn = false;
clearTimeout(counterAnimation);
mult = 1
counter = null
animationOn = false
counterAnimation = null
}
}
<body>
<button onclick="startAnimation();">
Start animation
</button>
<button onclick="stopAnimation();">
Stop animation
</button><br><br>
<label>Enter an integer: </label>
<input type="number" size=20 id=value1 name="value">
<span id="counterHolder">0</span>
</body>

Summing up input values inside a forEach function

I'm trying to add up range input values but for reasons I don't know it starts from 0 when I change the next inputs value. Could it be that I'm calling the function inside a forEach function? Any help would be appreciated.
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
var d=document,
range = d.querySelectorAll(".time-range"),
time_total_hrs = d.querySelectorAll(".time_total .hours"),
time_total_min = d.querySelectorAll(".time_total .minutes"),
timeMax = 1440,
timeInput = 0,
timeLeft,num,hours,rhours,minutes,rminutes,current;
function getCurrent(){
if (defined(slide)){
return current = d.querySelector(".slide.active");
}
}
getCurrent()
function timeConvert(num) {
hours = (num / 60);
rhours = Math.floor(hours);
minutes = (hours - rhours) * 60;
rminutes = Math.round(minutes);
return num + " min = " + rhours + " h and " + rminutes + " min.";
}
function updateTotalTime(){
var tot = 0;
for (i = 0; i < range.length; i++){
tot = tot + parseInt(range[i].value, 10);
}
console.log("total time is: "+tot+"");
return tot;
}
function updateTimeLeft(){
timeLeft = parseInt(timeMax) - parseInt(updateTotalTime());
timeConvert(timeLeft);
console.log("time left:"+timeLeft+"")
for (i = 0; i < time_total_hrs.length; i++){
time_total_hrs[i].innerHTML = rhours;
time_total_min[i].innerHTML = rminutes;
}
}
function updateTimeSelected(){
timeConvert(timeInput);
current.querySelector(".time_current .hours").innerHTML = rhours;
current.querySelector(".time_current .minutes").innerHTML = rminutes;
}
function setWarning(){
for (i = 0; i < time_total.length; i++){
time_total[i].classList.add("warning");
}
}
function removeWarning(){
for (i = 0; i < time_total.length; i++){
time_total[i].classList.remove("warning");
}
}
[].forEach.call(range, function(el, i, els) {
el.addEventListener('input', function() {
timeInput = this.value;
updateTotalTime();
updateTimeLeft();
updateTimeSelected();
[].forEach.call(els, function(el) {
if (el !== this) {
el.setAttribute("max", timeLeft);
if (timeLeft === 0){
el.style.opacity = "0.5";
el.setAttribute("disabled", "true");
setWarning()
} else if (timeLeft > 0){
el.removeAttribute("disabled");
removeWarning()
} else {
}
} else {
}
}, this);
});
});
It's tricky to work out what you're trying to do and what's not working for you. I wonder if it's better to stop thinking in terms of "looping over everything" and start thinking along the lines of "I have some ranges, let's add the values together.
var ranges = Array.prototype.slice.call(document.querySelectorAll(".time-range"));
// ...
var total = ranges.reduce(function (subTotal, input) {
return subTotal + parseInt(input.value, 10);
}, 0);
You'd then have the total number of minutes and you can do whatever you like with that.
var ranges = Array.prototype.slice.call(document.querySelectorAll(".time-range"));
var hoursElement = document.querySelector(".time_total .hours");
var minutesElement = document.querySelector(".time_total .minutes");
function minsToHoursMins(raw) {
var hours = Math.floor(raw / 60);
var minutes = raw - (hours * 60);
return [hours, minutes];
}
document.querySelector(".time-range-holder").addEventListener("input", function () {
var total = ranges.reduce(function (subTotal, input) {
return subTotal + parseInt(input.value, 10);
}, 0);
var timeParts = minsToHoursMins(total);
hoursElement.innerHTML = timeParts[0];
minutesElement.innerHTML = timeParts[1];
});
<div class="time-range-holder">
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
</div>
<div class="time_total">
<p>Hours: <span class="hours"></span></p>
<p>Minutes: <span class="minutes"></span></p>
</div>
let inputs = [...document.querySelectorAll('input')]
let button = document.querySelector('button')
const SUM = () => inputs.reduce((prev, { value }) => +prev + +value, 0)
button.addEventListener('click', () => console.log(SUM()))
<input value="1"/>
<input value="1"/>
<input value="1"/>
<button>SUM</button>

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