I need to show the time in a text type input in a dynamic way, that is to say that it is constantly changing. For this, they recommended me to use the following function, but I have not managed to make the time show correctly. What am I doing wrong ?
Javascript
function new_clock(){
clock = new Date()
hour = clock.getHours()
minutes = clock.getMinutes()
seconds = clock.getSeconds()
print_clock= hour + " : " + minutes + " : " + seconds
document.form_clock.clock_txt.value = print_clock
setTimeout("new_clock()",1000)
}
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<section onload="new_clock()">
<form name="form_clock">
<input type="text" name="clock_txt" size="10" id="clock_txt">
</form>
The selected response works well, however when implementing the clock, it causes the module actions to load much slower.
Javascript
var today = moment().format('YYYY-MM-DD');
function new_clock(){
clock = new Date() ;
hour = clock.getHours();
minutes = clock.getMinutes() ;
seconds = clock.getSeconds() ;
print_clock= today + " " + hour + ":" + minutes + ":" + seconds;
$("#fecha_registro").val(print_clock);
setInterval(new_clock, 1000);
}
new_clock();
do this https://jsfiddle.net/u1Lkd0ra/
in javascript
function new_clock(){
clock = new Date();
hour = clock.getHours();
minutes = clock.getMinutes();
seconds = clock.getSeconds();
print_clock= hour + " : " + minutes + " : " + seconds;
document.form_clock.clock_txt.value = print_clock;
setTimeout(new_clock,1000);
}
new_clock();
and HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<form name="form_clock">
<input type="text" name="clock_txt" size="10" id="clock_txt">
</form>
Use setInterval method instead of setTimeout. Code that looks like this:
setInterval(function() {
var clock = new Date();
var hour = clock.getHours();
var minutes = clock.getMinutes();
var seconds = clock.getSeconds();
var print_clock = hour + " : " + minutes + " : " + seconds;
console.log(print_clock);
}, 1000);
I haven't really touched javascript, but would setTimeout(new_clock, 1000) work?
This is based on what I read here:
javascript setTimeout() not working
EDIT:
OOOP! I GOT IT!
https://jsfiddle.net/7wkw14wd/
So basically, the function is correct...
The time-out thingo... once the timer is up, will call new_clock()...
But since the time-out thingo is IN the function, you need to start it off before the chain reaction of recursion can begin!
https://jsfiddle.net/chj51hc3/1/
HTML :
<section id="mySection">
<form name="form_clock">
<input type="text" name="clock_txt" size="10" id="clock_txt">
</form>
</section>
Javascript :
$("#mySection").ready(function new_clock() {
clock = new Date() ;
hour = clock.getHours();
minutes = clock.getMinutes() ;
seconds = clock.getSeconds() ;
print_clock= hour + " : " + minutes + " : " + seconds;
$("#clock_txt").val(print_clock);
setInterval(new_clock, 1000);
});
For setTimeout, you need to specify a function and not its name.
Use .ready() instead of onload.
And please use semicolons.
EDIT : Updated fiddle for your code structure
Related
I am trying to create a browser training button. When the user clicks the " Brench Press" button his "Strength" increases by a php file that i've set in the form action and it checks some values and inserts values to the database that shows up.
What my problem and what i would like some help with is to implement my clock function that sets a countdown from 30 seconds to 0. This should be a countdown that the users has to watch and wait for untill he can "train" again. So somehow i need to write this clock function to output after the php file has been loaded and not onclick on the button as of now. And also for the clock not to refresh it's countdown on page refresh but keep going.
What i tried to do is to create a session with the function call inside and send it to the site so it loads after the php file has loaded but it doesn't seem to work.
$_SESSION['CountDownBenchPress'] = "<script> countdown(); </script>";
var time = 30;
function countdown()
{
if(time==0)
{
window.location.reload();
}
else
{
tmptime = time;
dayTime = 24*60*60;
hourTime = 60*60;
minutesTime = 60;
days = Math.floor(tmptime/dayTime);
tmptime = tmptime - days*dayTime;
hours = Math.floor(tmptime/hourTime);
tmptime = tmptime - hours*hourTime;
minutes = Math.floor(tmptime/minutesTime);
tmptime = tmptime - minutes*minutesTime;
seconds = tmptime;
tidtext="";
if(days>0)
tidtext = days+ hours + " hours " + minutes + " minutes " + seconds + " seconds";
else if(hours>0)
tidtext = hours + " hours " + minutes + " minutes " + seconds + " seconds";
else
tidtext = minutes + " minutes " + seconds + " seconds";
document.getElementById('timer').innerHTML = tidtext;
time--;
setTimeout("countdown()", 1000);
}
}
<form class="" action="" method="">
<td data-th="Workout"><input type="submit" onclick="countdown()" name="" value="Bench Press"></td>
<div id="timer"></div>
</form>
var time = 30;
function countdown()
{
if(time==0)
{
window.location.reload();
}
else
{
tmptime = time;
dayTime = 24*60*60;
hourTime = 60*60;
minutesTime = 60;
days = Math.floor(tmptime/dayTime);
tmptime = tmptime - days*dayTime;
hours = Math.floor(tmptime/hourTime);
tmptime = tmptime - hours*hourTime;
minutes = Math.floor(tmptime/minutesTime);
tmptime = tmptime - minutes*minutesTime;
seconds = tmptime;
tidtext="";
if(days>0)
tidtext = days+ hours + " hours " + minutes + " minutes " + seconds + " seconds";
else if(hours>0)
tidtext = hours + " hours " + minutes + " minutes " + seconds + " seconds";
else
tidtext = minutes + " minutes " + seconds + " seconds";
document.getElementById('timer').innerHTML = tidtext;
time--;
setTimeout("countdown()", 1000);
}
}
<form class="" action="" method="">
<td data-th="Workout"><input type="button" onclick="countdown()" name="" value="Bench Press"></td>
<div id="timer"></div>
</form>
you must put input type="button" instead of submit. That's because the submit redirects you to the action page that you wrote in the form (in your case, nothing)
EDIT I didn't notice the auto-click part. To solve it, you must modify the body tag as it follows
<body onload="document.getElementById('clickme').click()">
and the button like this
<input type="button" id="clickme" onclick="countdown()" name="" value="Bench Press">
I would like assistance on making this clock I created in Javascript/HTML update in real-time.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script>
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
}
</script>
</head>
<body onload="timer()">
<div id="txt"></div>
<body>
<h1>Clock</h1>
</body>
</html>
Any help would be appreciated.
You should create an interval timer and just call your timer function every X milliseconds, as you are displaying millisecond precision you might want to keep this low like 100ms. I suggest using setInterval for this. Just put this in your script block:
setInterval(timer, 100);
Here is a full example:
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
}
setInterval(timer, 100);
<div id="txt"></div>
Use the setTimeout function (see window.setTimeout)
In your case:
Call the timer function and add
window.setTimeout(timer, 50);
at the very end of the function.
Example:
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
window.setTimeout(timer, 50);
}
timer();
<div id="txt"></div>
I am having an issue with the setInterval() function in javascript where it will print to my page once and it will not continue to do so. I was wondering if maybe this is a browser issue or something i did wrong.
function printTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
document.write(hours + ":" + minutes + ":" + seconds + "<br/>");
}
setInterval("printTime()", 1000);
Apart from the poor practice of using "functionName()" instead of just functionName, the code will never work if the interval is beyond the page loading.
document.write will wipe the page after load
Here is a better solution:
<div id="time"></div>
<script>
function pad(str) { return ("0"+str).slice(-2)}
function printTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
document.getElementById("time").innerHTML+=pad(hours) + ":" + pad(minutes) + ":" + pad(seconds) + "<br/>";
}
setInterval(printTime, 1000);
</script>
var dateObj = new Date();
var month = dateObj.getUTCMonth() +1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var nowhour = dateObj.getHours();
var nowday = dateObj.getUTCDate();
var hour = "03";
var min = "00";
var hour2 = "18";
var min2 = "00";
var hour3 = "21";
var min3 = "00";
if(hour == 03)
{
day++;
}
document.write(nowhour);
newdate = year + "/" + month + "/" + day;
hourdate = " " + hour + ":" + min;
hourdate2 = " " + hour2 + ":" + min3;
hourdate3 = " " + hour2 + ":" + min3;
$("#bifrost")
if(nowhour > hour && day > nowday)
{
.countdown(newdate + hourdate, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}else if(nowhour > hour2)
{
.countdown(newdate + hourdate2, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}else{
.countdown(newdate + hourdate3, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}
Hello, i wanna make a countdown timer for events. I have 3 different event time,i wanna show up coming event here is my javascript code.
can anyone help me ?
ps: sorry for my bad english.
If countdown is a global function, you do not need the period before the call, just
countdown(parameters ... );
If countdown is a jquery plugin you have, and you are trying to call it on the jQuery object you created before the if statements, you must do it like this
$("#bifrost").countdown(parameters ... );
And repeat the jQuery selector in each of your if statements.
There is built in function setTimeout(function,milliseconds,param1,param2,...). Please see for examples in here.
setTimeout(function_to_do, miliseconds to wait) - will be triggered once;
setInterval(function_to_do, miliseconds to wait) - will be triggered periodically.
By the way - function name can't start with dot - and you have three calls to something .countdown(... There is you error.
I'm currently programming a calculator which is divided into two sections. The first section is a textbox which takes a string (an activity the user has entered). The second section consists of 4 textboxes. Each textbox requires a number as input. In the second section of the calculator, the calculator textboxes are labeled days, hours, minutes, and seconds. The purpose of the calculator is to determine how much money after the activity is complete. The formula for the activity & code is shown below.
MoneyMadeDuringActivity = (NumOfDays * days) + (NumOfHours * hours) + (NumOfMinutes * minutes) + (NumOfSeconds * seconds)
$(document).ready(function () {
/**
* VARIABLES
***/
var activity = $('#txtActivity').text();
var c = new Calculator();
var days = $('#txtDays').text();
var hours = $('#txtHours').text();
var minutes = $('#txtMinutes').text();
var seconds = $('#txtSeconds').text();
var MoneyMadeDuringActivity = (days * c.per_day) + (hours + c.per_hour) + (minutes * c.per_minute) + (seconds * c.per_second);
function listen(event, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(event, func, false);
} else if (elem.attachEvent) {
var r = elem.attachEvent("on"+event, func);
return r;
}
}
listen("click", $("#btnCalculate"), (function() {
$("#CalcOutput").text(
"In the time it takes me to " + activity + ",<br />" + "Barack Obama makes " + "$" + MoneyMadeDuringActivity
);
});
});
My problem occurs with getting the output to work. I can't get anything to be displayed. I have the div tag with an id="CalcOutput", so I don't know why it won't display correctly. Please help.
I saw you're trying to insert html with the text method, this is wrong, you html method instead.
$("#CalcOutput").html(
"In the time it takes me to " + activity + ",<br />Barack Obama makes $" + MoneyMadeDuringActivity
);
EDIT
This way worked for me.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
//mocking up your Calculator class
function Calculator(){
this.per_day = 345665;
this.per_hour = 67845;
this.per_minute = 1234;
this.per_second = 789;
}
$(document).ready(function () {
function calculate(){
var activity = $('#txtActivity').val();
var c = new Calculator();
var days = +$('#txtDays').val();
var hours = +$('#txtHours').val();
var minutes = +$('#txtMinutes').val();
var seconds = +$('#txtSeconds').val();
var MoneyMadeDuringActivity = (days * c.per_day) + (hours + c.per_hour) + (minutes * c.per_minute) + (seconds * c.per_second);
$("#CalcOutput").html(
"In the time it takes me to " + activity + ",<br />Barack Obama makes $" + MoneyMadeDuringActivity
);
}
$("#btnCalculate").click(function() {
calculate();
});
});
</script>
</head>
<body>
activity:
<input type='text' id='txtActivity' value='foobar' /><br/>
days:
<input type='text' id='txtDays' value='3'/><br/>
hours:
<input type='text' id='txtHours' value='12'/><br/>
minutes:
<input type='text' id='txtMinutes' value='34'/><br/>
seconds:
<input type='text' id='txtSeconds' value='37' /><br/>
<button id='btnCalculate'>Calculate</button><br>
<div id="CalcOutput"></div>
</body>
</html>