How to create a JQuery Clock / Timer - javascript

I have a simple quiz application and I want display a nice timer / clock at the top of the page which shows the user how long they've been going for. (If I could somehow show them a timer for Total Quiz Time and also a second one for This Question Time that would be even cooler but I should be able to figure out how to do myself that once I've got one timer working.
My question is:
What's a nice, easy way to show a simple timer / clock using JQuery? (straight JS is also ok) I know how to check time, but how do I get incrementing seconds?
My own searches keep leading me to JQuery plugins (I want to roll my own) and also "event timers" which are not what I'm looking for...

You're looking for the setInterval function, which runs a function every x milliseconds.
For example:
var start = new Date;
setInterval(function() {
$('.Timer').text((new Date - start) / 1000 + " Seconds");
}, 1000);

setInterval as suggested by SLaks was exactly what I needed to make my timer. (Thanks mate!)
Using setInterval and this great blog post I ended up creating the following function to display a timer inside my "box_header" div. I hope this helps anyone else with similar requirements!
function get_elapsed_time_string(total_seconds) {
function pretty_time_string(num) {
return ( num < 10 ? "0" : "" ) + num;
}
var hours = Math.floor(total_seconds / 3600);
total_seconds = total_seconds % 3600;
var minutes = Math.floor(total_seconds / 60);
total_seconds = total_seconds % 60;
var seconds = Math.floor(total_seconds);
// Pad the minutes and seconds with leading zeros, if required
hours = pretty_time_string(hours);
minutes = pretty_time_string(minutes);
seconds = pretty_time_string(seconds);
// Compose the string for display
var currentTimeString = hours + ":" + minutes + ":" + seconds;
return currentTimeString;
}
var elapsed_seconds = 0;
setInterval(function() {
elapsed_seconds = elapsed_seconds + 1;
$('#box_header').text(get_elapsed_time_string(elapsed_seconds));
}, 1000);

################## JQuery (use API) #################
$(document).ready(function(){
function getdate(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if(s<10){
s = "0"+s;
}
if (m < 10) {
m = "0" + m;
}
$("h1").text(h+" : "+m+" : "+s);
setTimeout(function(){getdate()}, 500);
}
$("button").click(getdate);
});
################## HTML ###################
<button>start clock</button>
<h1></h1>

How about the best of both worlds? I combined the answer with the OP's format.
function pretty_time_string(num) {
return ( num < 10 ? "0" : "" ) + num;
}
var start = new Date;
setInterval(function() {
var total_seconds = (new Date - start) / 1000;
var hours = Math.floor(total_seconds / 3600);
total_seconds = total_seconds % 3600;
var minutes = Math.floor(total_seconds / 60);
total_seconds = total_seconds % 60;
var seconds = Math.floor(total_seconds);
hours = pretty_time_string(hours);
minutes = pretty_time_string(minutes);
seconds = pretty_time_string(seconds);
var currentTimeString = hours + ":" + minutes + ":" + seconds;
$('.timer').text(currentTimeString);
}, 1000);

A 24 hour clock:
setInterval(function(){
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
// Add leading zeros
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
hours = (hours < 10 ? "0" : "") + hours;
// Compose the string for display
var currentTimeString = hours + ":" + minutes + ":" + seconds;
$(".clock").html(currentTimeString);
},1000);
// 24 hour clock
setInterval(function() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
// Add leading zeros
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
// Compose the string for display
var currentTimeString = hours + ":" + minutes + ":" + seconds;
$(".clock").html(currentTimeString);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clock"></div>

If you can use jQuery with Moment.js (great library), this is the way:
var crClockInit1 = null;
var crClockInterval = null;
function crInitClock() {
crClockInit1 = setInterval(function() {
if (moment().format("SSS") <= 40) {
clearInterval(crClockInit1);
crStartClockNow();
}
}, 30);
}
function crStartClockNow() {
crClockInterval = setInterval(function() {
$('#clock').html(moment().format('D. MMMM YYYY H:mm:ss'));
}, 1000);
}
Start clock initialization with crInitClock(). It's done this way to synchronize seconds. Without synchronization, you would start 1 second timer in half of second and it will be half second late after real time.

var eventdate = new Date("January 01, 2014 00:00:00");
function toSt(n) {
s=""
if(n<10) s+="0"
return s+n.toString();
}
function countdown() {
cl=document.clock;
d=new Date();
count=Math.floor((eventdate.getTime()-d.getTime())/1000);
if(count<=0)
{cl.days.value ="----";
cl.hours.value="--";
cl.mins.value="--";
cl.secs.value="--";
return;
}
cl.secs.value=toSt(count%60);
count=Math.floor(count/60);
cl.mins.value=toSt(count%60);
count=Math.floor(count/60);
cl.hours.value=toSt(count%24);
count=Math.floor(count/24);
cl.days.value=count;
setTimeout("countdown()",500);
}
Hello, I've a similar assignment which involved creating a Javascript Countdown Clock. Here's the code I used. Plug the above code between the < script language="Javascript" >< /script > tags. Keep in mind that just having this javascript won't do much if you don't have the html to display the clock. I'll leave writing the html to you. Design the clock however you wish.

var timeInterval = 5;
var blinkTime = 1;
var open_signal = 'signal1';
var total_signal = 1;
$(document).ready(function () {
for (var i = 1; i <= total_signal; i++) {
var timer = (i == 1) ? timeInterval : (timeInterval * (i - 1));
var str_html = '<div id="signal' + i + '">' +
'<span class="float_left">Signal ' + i + ' : </span>' +
'<div class="red float_left"></div>' +
'<div class="yellow float_left"></div>' +
'<div class="green float_left"></div>' +
'<div class="timer float_left">' + timer + '</div>' +
'<div style="clear: both;"></div>' +
'</div><div class="div_separate"></div>';
$('.div_demo').append(str_html);
}
$('.div_demo .green').eq(0).css('background-color', 'green');
$('.div_demo .red').css('background-color', 'red');
$('.div_demo .red').eq(0).css('background-color', 'white');
setInterval(function () {
manageSignals();
}, 1000);
});
function manageSignals() {
var obj_timer = {};
var temp_i = parseInt(open_signal.substr(6));
if ($('#' + open_signal + ' .timer').html() == '0')
open_signal = (temp_i == total_signal) ? 'signal1' : 'signal' + (temp_i + 1);
for (var i = 1; i <= total_signal; i++) {
var next_signal = (i == total_signal) ? 'signal1' : 'signal' + (i + 1);
obj_timer['signal' + i] = parseInt($('#signal' + i + ' .timer').html()) - 1;
if (obj_timer['signal' + i] == -1 && open_signal == next_signal && total_signal!=1) {
obj_timer['signal' + i] = (timeInterval * (total_signal - 1)) - 1;
$('#signal' + i + ' .red').css('background-color', 'red');
$('#signal' + i + ' .yellow').css('background-color', 'white');
}
else if (obj_timer['signal' + i] == -1 && open_signal == 'signal' + i) {
obj_timer['signal' + i] = (timeInterval - 1);
$('#signal' + i + ' .red').css('background-color', 'white');
$('#signal' + i + ' .yellow').css('background-color', 'white');
$('#signal' + i + ' .green').css('background-color', 'green');
}
else if (obj_timer['signal' + i] == blinkTime && open_signal == 'signal' + i) {
$('#signal' + i + ' .yellow').css('background-color', 'yellow');
$('#signal' + i + ' .green').css('background-color', 'white');
}
$('#signal' + i + ' .timer').html(obj_timer['signal' + i]);
}
}
</script>

Here's #SLaks answer, but in pure ES6 JavaScript.
var start = new Date,
$timer = document.querySelector('.Timer');
setInterval(function(timestamp) {
$timer.innerText = `${timestamp - start) / 1000} Seconds`;
}, 1000);

Just used the #Uday answer code and build a reverse clock of hr:mm
Was just playing, so thought if anyone would might need this, so sharing the fiddle in comments (Dnt know why stackover flow is not allowing me to paste the link here)

var timeInterval = 5;
var blinkTime = 1;
var open_signal = 'top_left';
$(document).ready(function () {
$('#div_top_left .timer').html(timeInterval);
$('#div_top_right .timer').html(timeInterval);
$('#div_bottom_right .timer').html(timeInterval * 2);
$('#div_bottom_left .timer').html(timeInterval * 3);
$('#div_top_left .green').css('background-color', 'green');
$('#div_top_right .red').css('background-color', 'red');
$('#div_bottom_right .red').css('background-color', 'red');
$('#div_bottom_left .red').css('background-color', 'red');
setInterval(function () {
manageSignals();
}, 1000);
});
function manageSignals() {
var top_left_time = parseInt($('#div_top_left .timer').html()) - 1;
var top_right_time = parseInt($('#div_top_right .timer').html()) - 1;
var bottom_left_time = parseInt($('#div_bottom_left .timer').html()) - 1;
var bottom_right_time = parseInt($('#div_bottom_right .timer').html()) - 1;
if (top_left_time == -1 && open_signal == 'top_left') open_signal = 'top_right';
else if (top_right_time == -1 && open_signal == 'top_right') open_signal = 'bottom_right';
else if (bottom_right_time == -1 && open_signal == 'bottom_right') open_signal = 'bottom_left';
else if (bottom_left_time == -1 && open_signal == 'bottom_left') open_signal = 'top_left';
if (top_left_time == -1) {
if (open_signal == 'top_right') {
top_left_time = (timeInterval * 3) - 1;
$('#div_top_left .red').css('background-color', 'red');
$('#div_top_left .yellow').css('background-color', 'white');
$('#div_top_left .green').css('background-color', 'white');
}
else if (open_signal == 'top_left') {
top_left_time = timeInterval - 1;
$('#div_top_left .red').css('background-color', 'white');
$('#div_top_left .yellow').css('background-color', 'white');
$('#div_top_left .green').css('background-color', 'green');
}
}
if (top_right_time == -1) {
if (open_signal == 'bottom_right') {
top_right_time = (timeInterval * 3) - 1;
$('#div_top_right .red').css('background-color', 'red');
$('#div_top_right .yellow').css('background-color', 'white');
$('#div_top_right .green').css('background-color', 'white');
}
else if (open_signal == 'top_right') {
top_right_time = timeInterval - 1;
$('#div_top_right .red').css('background-color', 'white');
$('#div_top_right .yellow').css('background-color', 'white');
$('#div_top_right .green').css('background-color', 'green');
}
}
if (bottom_right_time == -1) {
if (open_signal == 'bottom_left') {
bottom_right_time = (timeInterval * 3) - 1;
$('#div_bottom_right .red').css('background-color', 'red');
$('#div_bottom_right .yellow').css('background-color', 'white');
$('#div_bottom_right .green').css('background-color', 'white');
}
else if (open_signal == 'bottom_right') {
bottom_right_time = timeInterval - 1;
$('#div_bottom_right .red').css('background-color', 'white');
$('#div_bottom_right .yellow').css('background-color', 'white');
$('#div_bottom_right .green').css('background-color', 'green');
}
}
if (bottom_left_time == -1) {
if (open_signal == 'top_left') {
bottom_left_time = (timeInterval * 3) - 1;
$('#div_bottom_left .red').css('background-color', 'red');
$('#div_bottom_left .yellow').css('background-color', 'white');
$('#div_bottom_left .green').css('background-color', 'white');
}
else if (open_signal == 'bottom_left') {
bottom_left_time = timeInterval - 1;
$('#div_bottom_left .red').css('background-color', 'white');
$('#div_bottom_left .yellow').css('background-color', 'white');
$('#div_bottom_left .green').css('background-color', 'green');
}
}
if (top_left_time == blinkTime && open_signal == 'top_left') {
$('#div_top_left .yellow').css('background-color', 'yellow');
$('#div_top_left .green').css('background-color', 'white');
}
if (top_right_time == blinkTime && open_signal == 'top_right') {
$('#div_top_right .yellow').css('background-color', 'yellow');
$('#div_top_right .green').css('background-color', 'white');
}
if (bottom_left_time == blinkTime && open_signal == 'bottom_left') {
$('#div_bottom_left .yellow').css('background-color', 'yellow');
$('#div_bottom_left .green').css('background-color', 'white');
}
if (bottom_right_time == blinkTime && open_signal == 'bottom_right') {
$('#div_bottom_right .yellow').css('background-color', 'yellow');
$('#div_bottom_right .green').css('background-color', 'white');
}
$('#div_top_left .timer').html(top_left_time);
$('#div_top_right .timer').html(top_right_time);
$('#div_bottom_left .timer').html(bottom_left_time);
$('#div_bottom_right .timer').html(bottom_right_time);
}

Related

How to replace "0:00" with "Collect" in timer button

In the last days I had asked a question how to make a button that is disabled for 1 minute and when it is clickable again +25 points are added to a div. The problem is: When the timer is over it says "0:00". Is there a way to replace the "0:00" with "Collect"? I found similar questions on stackoverflow but they didn't help me.
Here is my code:
$('#btn').prop('disabled',true);
startCountDown();
function getCounter(){
return parseInt($('#counter').html());
}
function setCounter(count) {
$('#counter').html(count);
}
$("#btn").click(function() {
setCounter(getCounter()+25);
$('#btn').prop('disabled',true);
startCountDown();
});
function startCountDown() {
var minutes = 0,
seconds = 59;
$("#countdown").html(minutes + ":" + seconds);
var count = setInterval(function() {
if (parseInt(minutes) < 0 || parseInt(seconds) <=0 ) {
$("#countdown").html(minutes + ":" + seconds);
clearInterval(count);
$('#btn').prop('disabled',false);
} else {
$("#countdown").html(minutes + ":" + seconds);
seconds--;
if (seconds < 10) seconds = "0" + seconds;
}
}, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="counter">0</div>
<button id="btn">
<span id="countdown">0:00</span>
</button>
UPDATE:
I have updated my code as you can see in the second snippet. Unfortunately, I now have the problem that the number 0:01 has been replaced with "Collect". (So: 0:03, 0:02, Collect(disabled), Collect(enabled)). Here is the code:
$('#btn').prop('disabled',true);
startCountDown();
function getCounter(){
return parseInt($('#counter').html());
}
function setCounter(count) {
$('#counter').html(count);
}
$("#btn").click(function() {
setCounter(getCounter()+25);
$('#btn').prop('disabled',true);
startCountDown();
});
function startCountDown() {
var minutes = 0,
seconds = 60;
$("#countdown").html(minutes + ":" + seconds);
var count = setInterval(function() {
if (parseInt(minutes) < 0 || parseInt(seconds) <=0 ) {
$("#countdown").html(minutes + ":" + seconds);
clearInterval(count);
$('#btn').prop('disabled',false);
} else {
$("#countdown").html(minutes + ":" + seconds);
seconds--;
if (seconds < 10) seconds = "0" + seconds;}
if (seconds == 0) {// replacing 0:00 with "Collect" is right here
$('#countdown').html("Collect");
}
}, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="counter">0</div>
<button id="btn">
<span id="countdown">Collect</span>
</button>
Hello GuciiBananaKing99,
I have found the solution to your problem. You need to add an if statement when seconds is 0. Then change $('#btn').html to "Collect".
Here is the full code:
function startCountDown() {
var minutes = 0,
seconds = 59;
$("#countdown").html(minutes + ":" + seconds);
var count = setInterval(function() {
if (parseInt(minutes) < 0 || parseInt(seconds) <=0 ) {
$("#countdown").html(minutes + ":" + seconds);
clearInterval(count);
$('#btn').prop('enabled',false);
} else {
$("#countdown").html(minutes + ":" + seconds);
seconds--;
if (seconds < 10) {seconds = "0" + seconds;}
if (seconds == 0) { // Check if seconds is 0
$('#btn').html("Collect"); // Change Btn's HTML to Collect
});
}
}, 1000);
}

JS AM/PM times always show AM

I am making a simple time calculator in javascript. I have converted the times into 12-hour instead of 24 hour time for simplicity, however the code I have for calculating am/pm always shows am. Any reason why this would be happening?
Here is my code:
function solveTime(x) {
var suffixSolve = (utcHours + x) % 24;
var suffix = "am";
if (utcHours > 12) {
var suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
and here is the code behind utcHours
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
Example here: http://codepen.io/markgamb/pen/gwGkbo
The issue is you should be checking whether suffixSolve is greater than 12 instead of utcHours, because utcHours does not change due to the value of x. Since you can shift the hours forward and backwards, I created a variable shift to handle that.
function solveTime(x) {
if (x < 0) {
var shift = 24 + x;
} else {
var shift = x;
}
var suffixSolve = (utcHours + shift) % 24;
var suffix = "am";
if (suffixSolve > 12) {
suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
solveTime(4);
solveTime(0);
solveTime(-8);
<div id="4"></div>
<div id="-8"></div>
<div id="0"></div>

How to refresh timer when click on link in javascript

I have countdown time for 15 seconds. It refreshes when 1 second on it. I also need refresh timer when user clicks at link on my website. I use cookie to provide no refreshing of timer when user refreshes page. Now when I click at link my timer refreshes but my old timer continues to countdown. As a result I have two timers and every second I see values from different timers. For example: I have countdown timer for 15 second. I click at link when value on timer was 7 seconds, and I see something like this: 15, 6, 14, 5, 13, 4, 12, 3 etc. But I need normal sequnce such 15, 14, 13 etc. What should I do for it? Below is my code:
// calls when I click at link
function rate(auct_id){
$.ajax({
type: 'POST',
url: '/auth/rate',
data: {'id': auct_id },
success: function(data) {
data = jQuery.parseJSON(data);
if (data.message) {
alert(data.message);
if (data.message != 'rates_count') {
windows.location = '/#openModal';
}
} else {
var new_price = data.price;
var new_login = data.login;
new_price += '<span> руб.</span>';
$('#price_' + auct_id).html(new_price);
$('#login_' + auct_id).html(new_login);
setTimer(auct_id, true);
}
}
});
}
function setTimer(id, update) {
var countdown4;
if(getCookie('countdown_' + id) && !update) countdown4 = getCookie('countdown_' + id);
else countdown4 = 15;
if (update) delete_cookie('countdown_' + id);
do_cd4(id, countdown4, update);
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
function convert_to_time(secs) {
secs = parseInt(secs);
hh = secs / 3600;
hh = parseInt(hh);
mmt = secs - (hh * 3600);
mm = mmt / 60;
mm = parseInt(mm);
ss = mmt - (mm * 60);
if (hh > 23) {
dd = hh / 24;
dd = parseInt(dd);
hh = hh - (dd * 24);
} else {
dd = 0;
}
if (ss < 10) {
ss = "0" + ss;
}
if (mm < 10) {
mm = "0" + mm;
}
if (hh < 10) {
hh = "0" + hh;
}
if (dd == 0) {
return (hh + ":" + mm + ":" + ss);
}
else {
if (dd > 1) {
return (dd + " day " + hh + ":" + mm + ":" + ss);
} else {
return (dd + " day " + hh + ":" + mm + ":" + ss);
}
}
}
// Our function that will do the actual countdown
do_cd4 = function(id, countdown4, update) {
//console.log(countdown4);
if (countdown4 < 1) {
countdown4 = 15;
do_cd4(id, countdown4);
} else {
$('#timer_' + id).html(convert_to_time(countdown4));
setTimeout(function() {
do_cd4(id, countdown4, update);
}, 1000);
}
setCookie('countdown_' + id, countdown4, 3);
countdown4 = countdown4 - 1;
}
The question has already been asked : Resetting a setTimeout
You need to keep a reference on your setTimeout, so you can clear it or restart it.

Javascript box that takes answer and updates

I've gone over this for hours trying different things and can't get it to work, I've made a dice that rolls every 10 seconds, the timer and the dice roll shows on screen and constantly updates the roll. I want to make a box that shows the previous 5 rolls of the dice and constantly updates. Not sure if I have to make separate function or add it to my existing function. Here is what I have so far.
<script type = "text/javascript">
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1;
die1.innerHTML = d1;
status.innerHTML = "Dice Roll "+diceTotal+".";
clearInterval(ticker);
startTimer(0000010); // start again
}
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(0000010);
</script>
One option would be to have 5 predefined divs and have them cleared/filled dynamically.
Another option is to keep the roll history in an array and fill the 'history element' from that array.
For example:
rolls.push(d1); //add roll to history
if(rolls.length > maxrollhistory)
rolls.shift();
die1.innerHTML = 'Previous rolls: ' + rolls.reduce(function(prev,cur){return '<span class="rollhistory">' + cur + ' </span>' + prev; }, '');
where rolls is the array containing the history. (rollhistory is a class I made up to format the results).
In the underlying example I took the liberty of restructuring the program to display the above (click here for fiddle ) :
var die1 = document.getElementById("die1"),
status = document.getElementById("status");
function startTimer(secs) {
var timeInSecs = parseInt(secs),
rolls = [],
rem = 0,
maxrollhistory = 5,
roll = function(){
var d1 = Math.floor(Math.random() * 6) + 1;
rolls.push(d1); //add roll to history
if(rolls.length > maxrollhistory)
rolls.shift();
die1.innerHTML = 'Previous rolls: ' + rolls.reduce(function(prev,cur){return '<span class="rollhistory">' + cur + ' </span>' + prev; }, '');
status.innerHTML = "Dice Roll "+ d1 +".";
},
tick = function(){
if (--rem <= 0) {
rem = timeInSecs;
roll();
}
var secs = rem;
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
setTimeout(tick,1000);
}
tick();
}
startTimer(10);
All you need is to append. Check the snippet added status.innerHTML += "Dice Roll "+diceTotal+".<br>";
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1;
die1.innerHTML = d1;
status.innerHTML = "Dice Roll "+diceTotal+".<br>" +status.innerHTML;
clearInterval(ticker);
startTimer(0000010); // start again
}
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(0000010);
<div id="countdown"></div> <div id="die1" class="dice">0</div> <h2 id="status" style="clear:centre;"></h2>

JS Code Works in jsbin and Not in jsfiddle or Chrome/Safari?

I am trying to figure out why this code is working only in jsbin and not in jsfiddle or in any web browser as an html/js file. I have tried debugging but cannot find a conclusion.
I made the mistake of coding directly in jsbin instead of a document. Any input would be appreciated.
http://jsbin.com/tuduxedohe/7/edit
http://jsfiddle.net/2rs1x5pz/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>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>
var currentTime = document.getElementById('time');
var hundreths = 0;
var seconds = 0;
var minutes = 0;
var t;
function startClock() {
function add() {
hundreths++;
if (hundreths > 99) {
hundreths = 0;
seconds++;
if (seconds > 59) {
seconds = 0;
minutes++;
}
if(minutes >= 10) {
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();
}
function timer() {
t = setTimeout(add, 1);
}
timer();
} // end function start clock
function stopTimer() {
document.getElementById("result").innerHTML = "<p>" + ("Your time is: " + minutes + " minutes, " + seconds + " seconds, " + "and " + hundreths + " hundreths") + "</p>";
clearTimeout(t);
}
function resetTimer() {
hundreths = 0;
seconds = 0;
minutes = 0;
currentTime.innerHTML = "00:00:00";
}
That is because by default the script is added in a onload handler in jsfiddle, so your methods is available only inside the scope of that closure. So it will be
window.onload=function(){
//your script is here
}
You are trying to access them in global scope when you are trying to call them from on<event>="" attributes which will give an error like Uncaught ReferenceError: startClock is not defined in your console.
Change the second dropdown in the left panel under Frameworks & Extensions to body/head in the left panel of fiddle to add the script without a wrapper function
Demo: Fiddle

Categories