Javascript box that takes answer and updates - javascript

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>

Related

I have create Stopwatch and I want to display laps in my HTML page in 4 columns and 4 rows on lap button click

I have created a stopwatch and I want to display laps in my HTML page on lap button click but in 4 columns.
Here is my complete code: https://jsfiddle.net/waqasumer/agru2bdL/
Index.html
<div class="row" id="laps">
</div>
Js
var min = 0;
var sec = 0;
var msec = 0;
var getMin = document.getElementById("min");
var getSec = document.getElementById("sec");
var getmsec = document.getElementById("msec");
var interval;
function timer() {
msec++
getmsec.innerHTML = msec;
if (msec >= 100) {
sec++;
if (sec <= 9) {
getSec.innerHTML = "0" + sec;
} else {
getSec.innerHTML = sec;
}
msec = 0;
} else if (sec >= 60) {
min++;
if (min <= 9) {
getMin.innerHTML = "0" + min;
} else {
getMin.innerHTML = min;
}
sec = 0;
}
}
function lapTimer() {
var Laps = document.getElementById('laps');
Laps.innerHTML += "<div>" + " " + getMin.innerHTML + ":" + getSec.innerHTML + ":" + getmsec.innerHTML + "</div>";
}
´´´
I believe this is a typical solution:
#laps > div {
width: 25%;
float: left;
}
This will lay out the laps in 4 columns, then repeat onto a new line once those 4 columns are populated.
If I understood this requirement correctly.

Javascript- How to reset button counter when timer reaches 0

I'm trying to get a simple click counter function to countdown the number of clicks users are left to use, where the number of clicks left will reset every 24 hours.
I've look through a few tutorials and implemented it visually in the alert once user has maxed the click. But how do I get about only resetting the count once the timer reaches 0.
HTML
<p><button onclick="clickCounter()" type="button">Click</button></p>
<div id="result"></div>
JavaScript
function clickCounter() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if((min + '').length == 1){
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if((sec + '').length == 1){
sec = '0' + sec;
}
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
if(Number(localStorage.clickcount) <= 0){
alert('You have max the number of connect \nTime left: '+ hours+':'+min+':'+sec);
localStorage.clickcount =4;
}
localStorage.clickcount = Number(localStorage.clickcount)-1
}
else
{
localStorage.clickcount = 4;
}
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks left.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
Here's a sample of how it's running. Currently I've set it to reset right after the alert pops out, and I'm just figuring how to reset automatically when the timer is up. Thanks for any feedback and help
sample link
You can set an interval function to check the time and reset values when time is up. I've changed your code to add a interval function
checkClickCount();
function clickCounter() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if ((min + '').length == 1) {
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if ((sec + '').length == 1) {
sec = '0' + sec;
}
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
if (Number(localStorage.clickcount) < 1) {
alert('You have max the number of connect \nTime left: ' + hours + ':' + min + ':' + sec);
return;
}
localStorage.clickcount = Number(localStorage.clickcount) - 1
} else {
localStorage.clickcount = 4;
}
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks left.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
var intv = null;
function checkClickCount(){
// interval run a function in a specified period of time
intv = window.setInterval(function(){
var currentTime = new Date();
var remainDateTime = new Date();
remainDateTime.setHours(24 - currentTime.getHours());
remainDateTime.setMinutes(60 - currentTime.getMinutes());
remainDateTime.setSeconds(60 - currentTime.getSeconds());
if(localStorage.clickcount > 1){
return;
}
// If the remaining times finished, the click count will be reset
if(remainDateTime.getHours() + remainDateTime.getMinutes() + remainDateTime.getSeconds() == 0){
localStorage.clickcount = 4;
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks";
return;
}
document.getElementById("result").innerHTML = "You will get 4 more clicks in " + remainDateTime.getHours() + ":" + remainDateTime.getMinutes() + ":" + remainDateTime.getSeconds() + " later.";
}, 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 Clock

I ran into a snag in my code, the code below is for a JavaScript clock which works perfectly:
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if(h == 0) {
h = 12;
} else if(h > 12) {
h = h - 12;
diem = "PM";
}
if(h < 10) {
h = "0" + h;
}
if(m < 10) {
m = "0" + m;
}
if(s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + ":" + s + " " + diem;
myClock.innerHTML = h + ":" + m + ":" + s + " " + diem;
myClock.innerText = h + ":" + m + ":" + s + " " + diem;
setTimeout('renderTime()',1000);
}
renderTime();
However I am trying to do it slightly different now like this:
function makeTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if(h == 0) {
h = 12;
} else if(h > 12) {
h = h - 12;
diem = "PM";
}
if(h < 10) {
h = "0" + h;
}
if(m < 10) {
m = "0" + m;
}
if(s < 10) {
s = "0" + s;
}
var clock = document.getElementById('clock');
clock.innerHTML = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
myClock.textContent = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
myClock.innerText = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
setTimeout('makeTime()',1000);
}
makeTime();
This one works, however does not update like the other one, you have to manually refresh the page.
What am I doing wrong?
You continue to refer to myClock in your second version, when you've renamed the variable to clock:
var clock = ...
clock.innerHtml = ...
myClock.textContent = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
myClock.innerText = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
setTimeout('makeTime()',1000);
This is causing errors (reference error: myClock is not defined) which is preventing the flow of execution from reaching your setTimeout call.
You should learn to use the tools available to you. Every browser has a method of reporting JavaScript errors to developers. Open the developer console in Webkit/IE10, or Firebug in Firefox, you'll see these errors and exactly where they're happening in your code.

Categories