Increase a series each time a function is called - javascript

I have divs displayed with a PHP script using foreach. Each div should call a JavaScript function and generate a new div unic with id but I don't know how to increment the series. I need a incrementing loop each time the a div calls the function. Is that possible?
This is the .php file:
<body>
<script type="text/javascript">
foreach($objects as $key => $ar1)
{
countdown_clock_abs(<?php echo $ar1['timespamSale']; ?>,1);
}
</script>
</body>
</html>
This is the JavaScript:
function countdown_clock_abs(time, format)
{
// I expected the foreach loop do the job but the php it is loaded before the javascrip is launched. So clearly this is not the way to do it.
html_code = '<div id="countdown<?php echo ar1['id']; ?>"></div>';
document.write(html_code);
countdown_abs(time, format);
}
function countdown_abs(time, format)
{
var d=new Date();
var Target_Time = (time);
var Now_time = ((d.getTime()));
Time_Left = Math.round(Target_Time-(Now_time)/1000);
if(Time_Left < 0)
Time_Left = 0;
var innerHTML = '';
switch(format)
{
case 0:
innerHTML = Time_Left + ' seconds';
break;
case 1:
days = Math.floor(Time_Left / (60 * 60 * 24));
Time_Left %= (60 * 60 * 24);
hours = Math.floor(Time_Left / (60 * 60));
Time_Left %= (60 * 60);
minutes = Math.floor(Time_Left / 60);
Time_Left %= 60;
seconds = Time_Left;
dps = 's'; hps = 's'; mps = 's'; sps = 's';
if(days == 1) dps ='';
if(hours == 1) hps ='';
if(minutes == 1) mps ='';
if(seconds == 1) sps ='';
innerHTML = days + ' day' + dps + ' ';
innerHTML += hours + ' hour' + hps + ' ';
innerHTML += minutes + ' minute' + mps + ' and ';
innerHTML += seconds + ' second' + sps;
break;
default: innerHTML = Time_Left + ' seconds';
}
document.getElementById('countdown<?php echo ar1['id']; ?>').innerHTML = innerHTML;
setTimeout('countdown_abs(' + time + ',' + format + ');', 50);
}

Modify the signature of your method to match function countdown_clock_abs(time, format, id). Now in your first block of code, you can pass the counter to the id param

Related

Set this countdown timer to specific time

I have a Javascript code for a countdown timer on a date. I want to use this code in a online shop order process. However I don't want to edit the date every day manually. I want that the timer counts everyday to the same target time.
Note: the variable responsible for that is: deadline
function updateTimer(deadline){
var time = deadline - new Date();
return {
'days': Math.floor( time/(1000*60*60*24) ),
'hours': Math.floor( (time/(1000*60*60)) % 24 ),
'minutes': Math.floor( (time/1000/60) % 60 ),
'seconds': Math.floor( (time/1000) % 60 ),
'total' : time
};
}
function animateClock(span){
span.className = "turn";
setTimeout(function(){
span.className = "";
},700);
}
function startTimer(id, deadline){
var timerInterval = setInterval(function(){
var clock = document.getElementById(id);
var timer = updateTimer(deadline);
clock.innerHTML = '<span>' + timer.days + '</span>'
+ '<span>' + timer.hours + '</span>'
+ '<span>' + timer.minutes + '</span>'
+ '<span>' + timer.seconds + '</span>';
//animations
var spans = clock.getElementsByTagName("span");
animateClock(spans[3]);
if(timer.seconds == 59) animateClock(spans[2]);
if(timer.minutes == 59 && timer.seconds == 59) animateClock(spans[1]);
if(timer.hours == 23 && timer.minutes == 59 && timer.seconds == 59) animateClock(spans[0]);
//check for end of timer
if(timer.total < 1){
clearInterval(timerInterval);
clock.innerHTML = '<span>0</span><span>0</span><span>0</span><span>0</span>';
}
}, 1000);
}
window.onload = function(){
var deadline = new Date("august 26, 2017 17:15:00");
startTimer("clock", deadline);
};

javascript manual countdown timer (based on the user input)

i want to make a countdown timer for a project in which the countdown start when the user inputs some time in 00:00:00 h-m-s format, i have written some code which is half correct and i'm lost what to do next
// Wait for user to click the button before reading the value
window.onload=function(){
var work = document.getElementById("dl");
work.addEventListener("click", handler);
}
function handler() {
//taking user input
var time1 = document.getElementById('hms').value;
//splitting it to seperate variables
var pieces = time1.split(":");
var hours = pieces[0];
var minutes = pieces[1];
var seconds = pieces[2];
//just calculating total number of seconds
seconds = seconds + minutes*60 + hours*3600;
var tot = seconds + minutes*60 + hours*3600;
// Save the interval's handle to `timer`
var timer = setInterval(countdown, 1000);
function countdown() {
var container = document.getElementById('count');
var counter = 0, k=1, j=1, i=0, s1= pieces[2];
//loop to print the timer
for(i=0; i<tot; i++){
if(seconds>0){
counter ++ ;
if(counter==60*k){
minutes--;
k++;
}
if(counter==3600*j){
hours--;
j++;
}
container.innerHTML = 'Please wait <b>' + hours + '</b> hours, <b>' + minutes + '</b> minutes, <b>' + seconds + '</b> seconds';
}//end of if
else {
container.innerHTML = 'Time over';
clearInterval(timer);
}
}
/* seconds--;
if (seconds > 0) {
container.innerHTML = 'Please wait <b>' + seconds + '</b> seconds..';
} else {
container.innerHTML = 'Time over';
clearInterval(timer);
} */
}
}
<input type="text" id="hms" placeholder="enter in the format 00:00:00 " />
<input type="button" id="dl" value="Start" />
<div id="count"></div>
i know i have made this complicated, can someone please make it simple? it will be a great help, thanks!
I have modified the function handler.You can try this.
function handler() {
//taking user input
var time1 = document.getElementById('hms').value;
//splitting it to seperate variables
var pieces = time1.split(":");
var hours = pieces[0];
var minutes = pieces[1];
var seconds = pieces[2];
var time = {
hours: hours * 1,
minutes: minutes * 1,
seconds: seconds * 1
};
// Save the interval's handle to `timer`
var timer = setInterval(countdown, 1000);
function countdown() {
var container = document.getElementById('count');
if (time.seconds > 0) {
time.seconds--;
}
else {
if (time.minutes > 0) {
time.minutes--;
time.seconds = 60;
}
else {
time.minutes = 60;
time.seconds = 60;
time.hours--;
}
}
if (time.hours >= 0) {
container.innerHTML = 'Please wait <b>' + time.hours + '</b> hours, <b>' + time.minutes + '</b> minutes, <b>' + time.seconds + '</b> seconds';
}
else {
container.innerHTML = 'Time over';
clearInterval(timer);
}
}
}

Online Quiz: how can I avoid timer getting refreshed when user click on refresh button in the browser toolbar/Status Bar?

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.

Daily countdown timer - Display Message at 21:57

I'm struggling to figure out how Date() works, I found this on the web and wanted to make a countdown that stops at 21:57 UTC Time. It currently displays the message at 21:00 and apears until 22:00.
I tried to add if(currenthours != 21 && currentminutes >= 57){ and always broke it and got the message. I want it to stop 3 minutes before 22:00 and display the message. After it gets to 22:00 restart the countdown for the next day at 21:57.
Any help will be greatly appreciated !
var date;
var display = document.getElementById('time');
setInterval(function(){
date = new Date( );
var currenthours = date.getUTCHours();
// alert(currenthours);
var currentminutes = date.getUTCMinutes();
// alert(currentminutes);
var hours;
var minutes;
var secondes;
if (currenthours != 21) {
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getUTCMinutes();
secondes = 60 - date.getUTCSeconds();
display.innerHTML = ('00' + hours).slice(-2) + ' HOURS ' + '<p>' +
('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
('00' + secondes).slice(-2) + ' SECONDS';
} else {
display.innerHTML = "IT'S 21:57";
}
},1000);
<div id='time'></div>
Made a fiddle
https://jsfiddle.net/5qrs0tcp/1/
This is what I ended up with :
/*
|================================|
| COUNTDOWN TIMER |
|================================|
*/
// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
Date.prototype.toISOTime = function() {
return this.getUTCHours() + ':' +
('0' + this.getUTCMinutes()).slice(-2) + ':' +
('0' + this.getUTCSeconds()).slice(-2);
}
}
// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
Date.prototype.timeDiff = function(date2) {
var diff = Math.abs(this - date2);
return timeobj = {
hours : (diff/3.6e6|0), // hours
minutes : ('0' + ((diff%3.6e6)/6e4|0)).slice(-2), // minutes
seconds : ('0' + ((diff%6e4)/1e3|0)).slice(-2) // seconds
}
}
}
function countDown() {
var now = new Date();
var limitHr = 19;
var limitMin = 55;
var limitDate = new Date(+now);
// Set limitDate to next limit time
limitDate.setUTCHours(limitHr, limitMin, 0, 0);
// var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
var msg = [];
var diff;
// If outside limitHr:limitMin to (limitHr + 1):00
if (now.getUTCHours() == limitHr && now.getUTCMinutes() >= limitMin) {
msg.push('Countdown stopped');
setTimeout(function(){
msg = ['Wait for it'];
var jsonCounter = {
stats : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
},5000);
var jsonCounter = {
stats : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
} else {
if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
var jsonCounter = {
hours : now.timeDiff(limitDate).hours,
minutes : now.timeDiff(limitDate).minutes,
seconds : now.timeDiff(limitDate).seconds,
validating : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
}
}
setInterval(countDown, 1000);
var daily_status;
setTimeout( function(){
setInterval( function() {
jsonfile.readFile(DailyGamePath, (err, obj) => {
daily_status={
hours: obj.hours,
minutes: obj.minutes,
seconds: obj.seconds,
stats: obj.stats,
validating: obj.validating
};
return daily_status;
});
}, 1000);
}, 3000);
setTimeout( function(){
io.sockets.on('connection', (socket) => {
setInterval( function() {
// var GameStatus=DailyGameStatus();
socket.broadcast.emit('stream', {hours:daily_status.hours, minutes:daily_status.minutes, seconds:daily_status.seconds, stats:daily_status.stats, validating:daily_status.validating});
}, 1000);
});
}, 3000);
Date objects are very simple, they're just a time value and some handy methods.
I think your logic just needs to be:
if (currenthours != 21 && currentminutes < 57) {
// set the out of hours message
} else {
// time is from 21:57 to 21:59 inclusive
}
The countdown doesn't quite work because you're counting to 00 not to 57, but otherwise there doesn't seem to be an issue.
var date;
var display = document.getElementById('time');
setInterval(function(){
date = new Date( );
var currenthours = date.getUTCHours();
var currentminutes = date.getUTCMinutes();
var hours;
var minutes;
var secondes;
var limitHr = 5; // Change these to required values
var limitMin = 02; // Using 5:12 for convenience
var message = 'Currently: ' + date.toISOString() + '<p>';
// Create new message if outside limitHr:limitMin to limitHr:59 inclusive
if (currenthours != limitHr || currentminutes < limitMin) {
if (currenthours <= limitHr) {
hours = limitHr - currenthours;
} else {
hours = limitHr + (24 - currenthours);
}
minutes = limitMin - date.getUTCMinutes();
minutes += minutes < 0? 60 : 0;
secondes = 60 - date.getUTCSeconds();
message += ('00' + hours).slice(-2) + ' HOURS ' + '<p>' +
('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
('00' + secondes).slice(-2) + ' SECONDS';
} else {
message += 'It\'s on or after ' + limitHr + ':' +
('0'+limitMin).slice(-2) + ' GMT';
}
// Display the message
display.innerHTML = message;
},1000);
<div id="time"></div>
Yes, the timer has issues but that wasn't part of the question. For a counter, it's simpler to just work in time differences, so I've added some methods to Date.prototype for ISO time (to be consistent with ISO Date) and time difference, then use those functions.
The function builds a Date for the end time so that calculations can use Date methods.
// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
Date.prototype.toISOTime = function() {
return this.getUTCHours() + ':' +
('0' + this.getUTCMinutes()).slice(-2) + ':' +
('0' + this.getUTCSeconds()).slice(-2) + '.' +
('00' + this.getUTCMilliseconds()).slice(-3) + 'Z';
}
}
// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
Date.prototype.timeDiff = function(date2) {
var diff = Math.abs(this - date2);
var sign = this > date2? '+' : '-';
return sign + (diff/3.6e6|0) + ':' + // hours
('0' + ((diff%3.6e6)/6e4|0)).slice(-2) + ':' + // minutes
('0' + ((diff%6e4)/1e3|0)).slice(-2) + '.' + // seconds
('00' + (diff%1e3)).slice(-3); // milliseconds
}
}
function countDown() {
var now = new Date();
var limitHr = 1;
var limitMin = 10;
var limitDate = new Date(+now);
// Set limitDate to next limit time
limitDate.setUTCHours(limitHr, limitMin, 0, 0);
var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
var diff;
// If outside limitHr:limitMin to (limitHr + 1):00
if (now.getUTCHours() != limitHr || now.getUTCMinutes() != limitMin) {
if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
msg.push(now.timeDiff(limitDate));
} else {
msg.push('It\'s after ' + limitHr + ':' + ('0'+limitMin).slice(-2));
}
document.getElementById('msgDiv2').innerHTML = msg.join('<br>');
}
window.onload = function() {
setInterval(countDown, 1000);
}
<div id="msgDiv2"></div>>
I've left the milliseconds in, round to seconds if you wish.
I've left the timer using setInterval, though I'd prefer to use setTimeout and manually calculate the time to just after the next full second so that it never skips. Most browsers using setTimeout will slowly drift so that they skip a second every now and then. Not really an issue unless you happen to see it, or compare it to the tick of the system clock.

Javascript timer How to replace digits with images?

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

Categories

Resources