I have this chunk of javascript that's kind of hacked around from http://www.developphp.com/view.php?tid=1248 and I am seeing an error of "undefined variable - broadcast".
function cdtd(broadcast) {
/* expected date format is Month DD, YYYY HH:MM:SS */
var nextbroadcast = new Date(broadcast);
var now = new Date();
var timeDiff = nextbroadcast.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
document.getElementById("countdown").innerHTML = "<a href=\"flconlineservices.php\">Internet broadcast in progress<\/a>";
/* Run any code needed for countdown completion here */
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById("daysBox").innerHTML = days + " d";
document.getElementById("hoursBox").innerHTML = hours + " h";
document.getElementById("minsBox").innerHTML = minutes + " m";
// seconds isn't in our html code (javascript error if this isn't commented out)
/*document.getElementById("secsBox").innerHTML = seconds + " s";*/
var timer = setTimeout('cdtd(broadcast)',1000);
}
"broadcast" is passed from the page with this <script type="text/javascript">cdtd("<?php echo $nextbroadcast; ?>");</script>. $nextbroadcast is based upon the date/time when the user views the page.
I tried var broadcast;, var broadcast = "";, and var broadcast = null;. Whenever I try to declare the variable, before the function, it breaks the script.
Am I doing something incorrectly? The script is working, just fine, but I'd rather not have the error.
Change the following line:
var timer = setTimeout('cdtd(broadcast)',1000);
To this:
var timer = setTimeout(function() { cdtd(broadcast); }, 1000);
This might be where the problem is:
var timer = setTimeout('cdtd(broadcast)',1000);
You should declare var timer; above cdtd() function, and then set it like so below or outside of the function:
var func = 'cdtd(' + broadcast + ')';
timer = setTimeout(func,1000);
Related
I tried to build a countdown timer and it kind of worked, but when I changed the code to make it more readable and when I added the stop button function it got a bit buggy. I fiddled around a lot, but I can't get it working again.
The problem I have is, that the countdown starts from the time when the page has loaded and not from the number assigned to "sessTime".
Here is the code (i know it is a lot, sorry):
var startButton = document.getElementById('btnStart');
var stopButton = document.getElementById('btnStop');
var sessionTime = parseInt(document.getElementById('sessNum').innerHTML); //gets duration number
var sessLength = Date.parse(new Date()) + sessionTime * 60 * 1000;
startButton.onclick = function() {
if (!sessTimer) {
startButton.value="Stop";
var sessTimer = setInterval(runSess, 1000);
}else{
startButton.value="Start";
clearInterval(sessTimer);
}
};
function runSess() {
var timeLeft = sessLength - Date.parse(new Date());
var seconds = Math.floor((timeLeft / 1000) % 60);
var minutes = Math.floor((timeLeft / 1000 / 60) % 60);
var hours = Math.floor((timeLeft / (1000 * 60 * 60)) % 24);
document.getElementById("hours").innerHTML = ('0' + hours).slice(-2);
document.getElementById("minutes").innerHTML = ('0' + minutes).slice(-2);
document.getElementById("seconds").innerHTML = ('0' + seconds).slice(-2);
if (timeLeft <= 0) {
clearInterval(sessTimer);
}
}
This code is part of a codepen project of mine. Maybe the context helps to answer this question.
Thanks in advance, I really appreciate your help.
You have declared sessTimer inside the scope of your function.
startButton.onclick = function() {
if (!sessTimer) {
startButton.value="Stop";
var sessTimer = setInterval(runSess, 1000);
With the code above, every time you enter the function, sessTimer is undefined and you declare a new one. What you can do is the following :
var sessTimer = null;
startButton.onclick = function() {
if (!sessTimer) {
startButton.value="Stop";
sessTimer = setInterval(runSess, 1000);
}else{
startButton.value="Start";
clearInterval(sessTimer);
sessTimer = null;
}
};
Into you function, you also need to change your button :
if (timeLeft <= 0) {
startButton.value="Start";
clearInterval(sessTimer);
}
I'm working on a countdown timer and I have this piece of code right now. I took it from a different post and modified it a bit. I probably don't have to explain how the script works but here is the way I want it to work:
Set a startdate and enddate in the html attributes.
Pass that data into two variables 'dataStart' and 'dataEnd'.
Use the 'dataStart' as startdate and use the 'dataEnd' as enddate.
Countdown from startdate to enddate like this:
If the startdate is in the future, don't start the countdown yet but
let it start as soon as the startdate = the currentdate.
If the startdate is in the past, start the countdown but display the amount
of days, hours, minutes and seconds left from the currentdate to the
enddate.
var dataEnd = document.getElementById('countdown').getAttribute("data-end");
var dataStart = document.getElementById('countdown').getAttribute("data-start");
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
var tiles = document.getElementById('tiles');
var tilesClass = document.getElementById('tiles').classList;
var countLabel = document.getElementById('countdown-label');
var countDiv = document.getElementById('countdown');
function showRemaining() {
var end = new Date(dataEnd);
var start = new Date();
var distance = end - start;
if (distance < 0) {
clearInterval(timer);
// Replaces the countdown tiles with '---' & the label with 'SALE IS OVER'.
tiles.innerHTML = '---';
countLabel.innerHTML ='SALE IS OVER!';
// Sets display to none, so when the countdown is finished it will NOT be visible anymore.
countDiv.style.display = 'none';
return;
} if (distance < _hour ) {
// Removes the Orange background and adds the Red background.
tilesClass.remove('color-half');
tilesClass.add('color-empty');
countLabel.innerHTML ='HURRY! SALE ENDS IN:';
} else {
// Sets display to block, so when the countdown is NOT finished it will be visible.
countDiv.style.display = 'block';
}
var days = pad(Math.floor(distance / _day));
var hours = pad(Math.floor((distance % _day) / _hour));
var minutes = pad(Math.floor((distance % _hour) / _minute));
var seconds = pad(Math.floor((distance % _minute) / _second));
tiles.innerHTML = days + ':';
tiles.innerHTML += hours + ':';
tiles.innerHTML += minutes + ':';
tiles.innerHTML += seconds + '';
}
timer = setInterval(showRemaining, 1000);
function pad(n) {
return (n < 10 ? '0' : '') + n;
}
I have basic javascript knowledge but can't figure this out myself...
I am using an API that returns the time like this deal_expiration_time:1469396377 which looks like its seconds from 1970. I am trying to get a countdown in MM/SS This is in angular so I apparently can't use jQuery? I have struggled for a while and am stumped with this code. I'm trying to make it so its input: 1469396377 | output: 08:21
function(){
var x1, secs1 = 510;
x1 = setInterval(function(){myFunc1(9)}, 1000);
function myFunc1(timerId){
var minutes = Math.floor(secs1 / 60);
var seconds = secs1 % 60;
$('#timer_'+timerId).html(minutes + ':' + seconds); //assuming there is a label with Id 'timer'
secs1--;
if(secs1 == 0){
document.getElementById('timer_' + timerId).style.hidden = true;
clearInterval(x1);
}
}
}
You can get the current time using Date.now() and then manually calculate the difference in time. This function gets the difference between the given time and the current time, calculates the difference in seconds and in minutes. This difference is then formatted as a countdown string and then returned.
function getTimeDifference(expirationTime) {
var now = Date.now();
var diff = expirationTime - now;
var secDiff = Math.round(diff/1000);
var minDiff = Math.round(secDiff / 60);
var diffStr = minDiff + ":" + (secDiff - minDiff * 60);
return diffStr
}
I am trying to implement a countdown timer using jQuery. I have an end time and the timer should count down from it until the current time becomes same as it.
I get the end time from a web service which I fetch using PHP an the end time that I get looks like this 2015-07-15 17:29:31.
My actual line of code is like this
var then=<?php echo $server_response; ?>;
which I changed in the fiddle for easy understanding like this
var then='2015-07-15 17:29:31';
Here's the JavaScript code:
var timer;
var then='2015-07-15 17:29:31';
var now = new Date();
//now.setDate(now.getDate() + 7);
var compareDate=then.getDate()-now.getDate();
timer = setInterval(function() {
timeBetweenDates(compareDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = toDate;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
}
HTML
<div id="timer">
<span id="days"></span>days
<span id="hours"></span>hours
<span id="minutes"></span>minutes
<span id="seconds"></span>seconds
</div>
Fiddle
To get the date from string use new Date(date).
See the changes:
var compareDate = new Date(then) - now.getDate();
// ^^^^^^^^^^^^^^ instead of then.getDate()
In timeBetweenDates()
var dateEntered = new Date(toDate);
// ^^^^^^^^^^^^^^^^^ Parse to date instead of using it as it is
Demo
EDIT
Also change the way you're getting date from server. Wrap it in quotes.
var then = '<?php echo $server_response; ?>'; // String
My javascriptcode is working fine when i put alert.I need to Display time in Counter Format(Second decreasing way). Please help me in resolving this issue
<script type="text/javascript">
window.onload = function () {
//alert("request>>>");
var count = 0;
var start_actual_time = document.getElementById("timerStartTime").value;
var end_actual_time = document.getElementById("timerEndTime").value;
start_actual_time = new Date(start_actual_time);
var start_actual_time1 = new Date(start_actual_time.getTime());
start_actual_time1 = new Date(start_actual_time1);
var end_actual_time1 = new Date(end_actual_time);
var hours =end_actual_time1.getHours()- start_actual_time1.getHours();
var minutes = end_actual_time1.getMinutes() - start_actual_time1.getMinutes();
var seconds = end_actual_time1.getSeconds()- start_actual_time1.getSeconds();
seconds = hours * 3600 + minutes * 60 + seconds;
//alert ("seconds >>." +seconds);
timer(seconds);
};
function timer(seconds) {
alert("calling timer");
var s1 = Number(seconds);
var hours = Math.floor(s1 / 3600);
var minutes = Math.floor(s1 % 3600 / 60);
var s = Math.floor(s1 % 3600 % 60);
//alert("sec1" + s);
display = document.querySelector('#time');
var formatted = ((hours < 10)?("0" + hours):hours) + ":" + ((minutes < 10)?("0" + minutes):minutes) + ":" + ((s < 10)?("0" + s):s)
display.textContent = formatted ;
seconds = seconds - 1;
timer(seconds);
}
</script>
The way your code is written creates a
too much recursion
exception for me.
Therefore I have avoided recursive invokes and used javascript setInterval:
var refreshIntervalId = setInterval(function(){ timer(); }, 1000);
When your seconds reach zero, timer is stopped:
if (seconds == -1){
clearInterval(refreshIntervalId);
Link to working fiddle: http://jsfiddle.net/3ggspruf/2/