I'm trying to create a time-based count down clock. It is not based upon current_dates. The initial time that will be pulled will be from a separate php file. This will be for a browser based-game. When someone clicks the button to initiate this script. it will check if certain requirements are met and if so then this script will initiate. Based upon the level of the object it will pull the initial timer for that proceeding level. Hope that makes sense. Anyhow I based the timer script off of the first code I provide.
This script only accounts for minutes and seconds. I modified it to include days and hours as well. Somewhere in the process I have messed up and the script doesn't even work at all. I'm also not quite sure if this would be the best method to calculate this. So, if you have a cleaner method at doing this please share. Thank you in advance.
This script is based off of a minutes / seconds script I saw. Here's the original source:
<span id="countdown" class="timer"></span>
<script>
var seconds = 60;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
Here is the modified script that I am trying to include days, hours, minutes and seconds.
<span id="countdown"></span>
<script>
var current_level = 93578;
function timer() {
var days = Math.round(current_level/86400);
var remainingDays = Math.round(current_level - (days * 86400));
if (days <= 0){
days = current_level;
}
var hours = Math.round(remainingDays/3600);
var remainingHours = Math.round(remainingDays - (hours * 3600));
if (hours >= 24){
hours = 23;
}
var minutes = Math.round(remainingHours/60);
var remainingMinutes = Math.round(remainingHours - (minutes * 60));
if (minutes >= 60) {
minutes = 59;
}
var seconds = Math.round(remainingMinutes/60);
document.getElementById('countdown').innerHTML = days + ":" + hours ":" + minutes + ":" + seconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
I finally got back to looking at this and re-wrote the code and this works like a charm.
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
<span id="countdown" class="timer"></span>
Personally I would use the jquery countdown timer integration. It is simple and having number of options to display in different formats. Since I am fairly new to JS as well, this was the easiest way I found to get a count/timer.
http://keith-wood.name/countdown.html
Here is my worked out and tested example, based on your code
<span id="countdown"></span>
<script>
var current_level = 3002;
function timer() {
var days = Math.floor(current_level/86400);
var remainingDays = current_level - (days * 86400);
//if (days <= 0){
// days = current_level;
//}
var hours = Math.floor(remainingDays/3600);
var remainingHours = remainingDays - (hours * 3600);
//if (hours >= 24){
// hours = 23;
//}
var minutes = Math.floor(remainingHours/60);
var remainingMinutes = remainingHours - (minutes * 60);
//if (minutes >= 60) {
// minutes = 59;
//}
var seconds = remainingMinutes;
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + seconds;
//if (seconds == 0) {
// clearInterval(countdownTimer);
// document.getElementById('countdown').innerHTML = "Completed";
//}
current_level--;
}
var countdownTimer = setInterval(timer, 1000);
</script>
This code will help you deal with the issue of handling multiple timer on the single page
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');
var total_timers = seconds_inputs.length;
for ( var i = 0; i < total_timers; i++){
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var cal_seconds = seconds_inputs[i].getAttribute('value');
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
}
function timer() {
for ( var i = 0; i < total_timers; i++) {
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);
if (eval('seconds_'+ seconds_prod_id) == 0) {
clearInterval(countdownTimer);
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
} else {
var value = eval('seconds_'+seconds_prod_id);
value--;
eval('seconds_' + seconds_prod_id + '= ' + value + ';');
}
}
}
var countdownTimer = setInterval('timer()', 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
<div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>
</div>
const Panel = ({ label, n }) => (
<div className="panel">
<small>{label}</small>
<span>{n < 10 ? '0' + n : n}</span>
</div>
)
const App = () => {
const [secondsLeft, setSecondsLeft] = React.useState(86403)
React.useEffect(() => {
const interval = setInterval(() => {
if (secondsLeft == 0) {
clearInterval(interval)
console.log('Times up!')
} else {
setSecondsLeft(secondsLeft - 1)
}
}, 1000)
return () => clearInterval(interval)
})
const days = Math.floor(secondsLeft / 24 / 60 / 60)
const hoursLeft = Math.floor(secondsLeft - days * 86400)
const hours = Math.floor(hoursLeft / 3600)
const minutesLeft = Math.floor(hoursLeft - hours * 3600)
const minutes = Math.floor(minutesLeft / 60)
const seconds = secondsLeft % 60
return (
<div className="root">
<Panel label="Days" n={days} />
<Panel label="Hours" n={hours} />
<Panel label="Minutes" n={minutes} />
<Panel label="Seconds" n={seconds} />
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
.root {
display: flex;
}
.panel {
display: flex;
flex-direction: column;
align-items: center;
margin-right: 8px;
color: #444;
}
.panel small {
font-size: 9px;
text-transform: uppercase;
font-family: sans-serif;
}
.panel span {
font-size: 3em;
font-weight: bold;
font-family: serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
<span id="countdown" class="timer"></span>
Related
I have one file main.js. With 2 functions
function clockDown(scs,ids){
var countdownTimer = setInterval(function(){
$(".trf_"+ids).html(timer(scs));
scs--;
}, 1000);
}
function timer(seconds){
var seconds = seconds;
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
return (days + ":" + hours + ":" + minutes + ":" + remainingSeconds);
if (seconds == 0) {
return ("Completed");
} else {
seconds--;
}
}
I include this file at the bottom of the page. In middle of page I am trying call function but zero results
<li>
<script type="text/javacsript">$(document).ready(function(){ clockDown($timeLeft,$PostCoinJoinedItemsId); });</script>
</li>
What I doing wrong?
But calling a function in main.js is working well
I've tested, and it works just fine. You have a typo
type="text/javacsript"
<!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="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="trf_"></div>
<li>
<script type="text/javascript">
$(document).ready(function () {
clockDown(10, '');
});
</script>
</li>
<script>
function clockDown(scs, ids) {
var countdownTimer = setInterval(function () {
$(".trf_" + ids).html(timer(scs));
scs--;
}, 1000);
}
function timer(seconds) {
var seconds = seconds;
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
return (days + ":" + hours + ":" + minutes + ":" + remainingSeconds);
if (seconds == 0) {
return ("Completed");
} else {
seconds--;
}
}
</script>
</body>
</html>
htmlTable.Append("<script> var seconds = " + ttime + "; function secondPassed() { var minutes = Math.round((seconds - 30) / 60); var remainingSeconds = seconds % 60; if (remainingSeconds < 10) { remainingSeconds = '0' + remainingSeconds; } document.getElementById('countdown').innerHTML = 'Time Left :- ' + minutes + ':' + remainingSeconds; if (seconds == 0) { clearInterval(countdownTimer);document.getElementById('Button1').click(); } else { seconds--; } } var countdownTimer = setInterval('secondPassed()', 1000);</script>");
PlaceHolder1.Controls.Add(new Literal { Text = htmlTable.ToString() });
The above code is used to create a timer in .aspx.cs file. It's an online exam application.
As my homework I have to prepare an asp webpage for database frontpage. To gain some extra points we can add a javascript. I deceided to add a clock I've found somewhere in script tutorials and modified it a little, but my skills are not enough to place it correctly
I want to place it in my MasterPage, but whole page dissapears only the clock lefts if I add it like this:
<div id="Zawartosc" onload="showTheTime();">
<%-- clock --%>
<script src="Script.js"></script>
</div>
and here is the clock script:
function showTheTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var ampm = "am";
var colon = '<IMG SRC="clock/colon.gif">';
if (hours < 10) hours = "0" + hours;
else hours = hours + '';
if (minutes < 10) minutes = "0" + minutes;
else minutes = minutes + '';
if (seconds < 10) seconds = "0" + seconds;
else seconds = seconds + '';
document.write('<IMG SRC="clock/' + hours.charAt(0) + '.gif">');
document.write('<IMG SRC="clock/' + hours.charAt(1) + '.gif">');
document.write(colon);
document.write('<IMG SRC="clock/' + minutes.charAt(0) + '.gif">');
document.write('<IMG SRC="clock/' + minutes.charAt(1) + '.gif">');
document.write(colon);
document.write('<IMG SRC="clock/' + seconds.charAt(0) + '.gif">');
document.write('<IMG SRC="clock/' + seconds.charAt(1) + '.gif">');
}
setTimeout("showTheTime()", 1000);
showTheTime();
could you please lead or help me to correct code and make the clock appear correctly with my page?
From w3schools.com
The write() method is mostly used for testing: If it is used after an
HTML document is fully loaded, it will delete all existing HTML.
Give this a try:
<div id="Zawartosc" onload="showTheTime();">
<script src="Script.js"></script>
</div>
function createElementImg(source) {
var img = document.createElement('img');
img.src = source;
return img;
}
function showTheTime() {
var clockEle = document.getElementById("Zawartosc");
while (clockEle.hasChildNodes()) {
clockEle.removeChild(clockEle.lastChild);
}
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var ampm = "am";
var colon = "clock/colon.gif";
if (hours < 10) hours = "0" + hours;
else hours = hours + '';
if (minutes < 10) minutes = "0" + minutes;
else minutes = minutes + '';
if (seconds < 10) seconds = "0" + seconds;
else seconds = seconds + '';
clockEle.appendChild(createElementImg("clock/' + hours.charAt(0) + '.gif"));
clockEle.appendChild(createElementImg("clock/' + hours.charAt(1) + '.gif"));
clockEle.appendChild(createElementImg(colon));
clockEle.appendChild(createElementImg("clock/' + minutes.charAt(0) + '.gif"));
clockEle.appendChild(createElementImg("clock/' + minutes.charAt(1) + '.gif"));
clockEle.appendChild(createElementImg(colon));
clockEle.appendChild(createElementImg("clock/' + seconds.charAt(0) + '.gif"));
clockEle.appendChild(createElementImg("clock/' + seconds.charAt(1) + '.gif"));
}
setTimeout("showTheTime()", 1000);
showTheTime();
I have created a countdown timer. However, it does not count down properly. Instead of counting down per second or minutes, it counts down by hundreths and does not update properly. I created another counting up timer using the same code but it works properly counting up per increment - it counts up minutes everytime 60 seconds have passed. I'm wondering how I can make this timer count down properly.
JSBin:
http://jsbin.com/funiveremi/6/edit
Updated* Adding in the 60 Seconds Counter:
http://jsbin.com/hohusuvube/2/edit
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>User Input Timer</title>
<script type="text/javascript" src="part2.js"></script>
</head>
<body>
<h1><div id="time">00:00:00</div></h1>
<div id="result"></div>
<button id="start" onclick ="startClock();" >Start</button>
<button id="stop" onclick="stopTimer();">Stop</button>
<button id="clear" onclick="resetTimer();">Reset</button>
</body>
</html>
JAVASCIPT
hundreths = 10;
seconds = 15;
minutes = 20;
document.getElementById("time").innerHTML = minutes + ":" + seconds + ":" + hundreths;
var currentTime = document.getElementById('time');
var t;
function startClock() {
function add() {
hundreths--;
if (hundreths < 0) {
hundreths = 0;
seconds--;
if (seconds < 0) {
seconds = 0;
minutes--;
}
if(minutes < 0) {
seconds= 0;
minutes= 0;
stopTimer();
}
}
if (hundreths > 9 && seconds < 9) {
currentTime.innerHTML = "0" + minutes + ":" + "0" + seconds + ":" + hundreths;
}
else if ((seconds > 9 ) && (hundreths < 9)) {
currentTime.innerHTML = "0" + minutes + ":" + seconds + ":" + "0" + hundreths;
}
else if((seconds > 9) && (hundreths > 9)) {
currentTime.innerHTML = "0" + minutes + ":" + seconds + ":" + hundreths;
}
else if ((minutes > 9) && (seconds < 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + "0" + seconds + ":" + "0" + hundreths;
}
else if ((minutes > 9) && (seconds > 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + seconds + ":" + "0" + hundreths;
}
else if ((minutes > 9) && (seconds > 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + seconds + ":" + hundreths;
}
else {
currentTime.innerHTML = "0" + minutes + ":" + "0" + seconds + ":" + "0" + hundreths;
}
timer();
} // end function add();
function timer() {
t = setTimeout(add, 100);
}
timer();
} // end function startClock();
function stopTimer() {
document.getElementById("result").innerHTML = "<p>" + ("Your time is: " + minutes + " minutes, " + seconds + " seconds, " + "and " + hundreths + " hundreths") + "</p>";
clearTimeout(t);
} // end function stopTimer();
function resetTimer() {
clearTimeout(t);
currentTime.innerHTML = "00:00:00";
} // end function resetTimer();
Just use the Jquery Countdown plugin.
http://hilios.github.io/jQuery.countdown/
The implementation will be easier. something like this.
<div id="getting-started"></div>
<script type="text/javascript">
$("#getting-started").countdown("2016/01/01", function(event) {
$(this).text(event.strftime('%D days %H:%M:%S'));
});
</script>
This will work, you had the logic about when to set seconds incorrect so it was constantly resetting itself. One of the best things to do in these kinds of cases if you're stuck is to simply try changing the if statements, remove some of them and play with different values. It can help teach you what's really happening in a system, and give you a clue as to what is wrong. Another tip is just to read the code aloud to yourself in normal English. As you read it aloud you will often realize you're mistakes by hearing yourself say the logic.
hundreths--;
if (hundreths < 0) {
hundreths = 10;
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
}
if(minutes < 0) {
seconds= 0;
minutes= 0;
stopTimer();
}
}
Hello how can I replace digits in following javascript timer with respective images. ie 0 with dig1.png, 1 with dig2.png, 3 with dig3. png.....colon(:) with colo.png.
00:23:01 ==>>
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
doSubmit();
document.getElementById("timeisup").innerHTML = "Time is up response.";
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
Timer.innerHTML = TotalSeconds;
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":"
+ LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : + Time;
}
And here is the html markup that shows the timer...
<span id="timer"style="font-weight: bold;"></span><script
type="text/javascript">window.onload = CreateTimer("timer", 7200);</script>
Thanks
I think the best approach is to create the images first and leave them in place
<img id="d0" src="dig0.png">
<img id="d1" src="dig0.png">
<img src="col.png">
<img id="d2" src="dig0.png">
<img id="d3" src="dig0.png">
<img src="col.png">
<img id="d4" src="dig0.png">
<img id="d5" src="dig0.png">
and then just update image src from javascript:
var digits = [document.getElementById("d0"),
document.getElementById("d1"),
document.getElementById("d2"),
document.getElementById("d3"),
document.getElementById("d4"),
document.getElementById("d5")];
function setTime(hh, mm, ss) {
digits[0].src = "dig" + Math.floor(hh / 10) + ".png";
digits[1].src = "dig" + (hh % 10) + ".png";
digits[2].src = "dig" + Math.floor(mm / 10) + ".png";
digits[3].src = "dig" + (mm % 10) + ".png";
digits[4].src = "dig" + Math.floor(ss / 10) + ".png";
digits[5].src = "dig" + (ss % 10) + ".png";
}
Old fashion and not Optimal:
First, create the HTML DOM objects:
var image = document.createElement("img");
image.className = "style here";
//image.style can come here ...
image.src = "Path/to/image/here";
Or pre-populate image with
<image src="path/to/image" id="imageId like ie0">
And Append them to the div you want in your Tick function:
var parentDiv = document.getElementById("parent div ID");
parentDiv.appendChild(image);
Modern way of doing it:
Include CSS in your code. You can add pretty styles and no worries for the images as it will be slow and somewhat inconsistent. See a live example with open source code is here: Minimal Digital Clock with CSS