Counter App: Button function to trigger various if else messages - javascript

I'm building a passenger counter application for buses with vanilla javascript and I'm trying to wrap my head around how, when clicking a HTML DOM Object button, will alter the messages I want to output based on where the count is.
I have an increase and decrease button that increase or decrease the count by 1. Each bus has different passenger capacities, so I've placed each three busses in the navbar (dds, ddsb, mci). When clicking "dds" for example, I want specific messages to be called relative to where the count is. Likewise for other bus models.
let messageEl = document.getElementById("message-el")
let countEl = document.getElementById("count-el")
let ddsNavEl = document.getElementById("dds-nav-el")
let ddsbNavEl = document.getElementById("ddsb-nav-el")
let mciNavEl = document.getElementById("mci-nav-el")
let increaseEl = document.getElementById("increase-btn")
let decreaseEl = document.getElementById("decrease-btn")
let increaseFiveEl = document.getElementById("increaseFive-btn")
let decreaseFiveEl = document.getElementById("decreaseFive-btn")
var count = 0
/* BASIC COUNTER FUNCTIONALITY WITH NO SEATING LIMIT WARNINGS */
function increase() {
count++
countEl.textContent = count
}
function decrease() {
count--
countEl.textContent = count
}
function increaseFive() {
count += 5
countEl.textContent = count
}
function decreaseFive() {
count -= 5
countEl.textContent = count
}
function reset() {
messageEl.textContent = "";
countEl.textContent = 0
count = 0
ddsNavEl.style.fontWeight = "normal";
ddsbNavEl.style.fontWeight = "normal";
mciNavEl.style.fontWeight = "normal";
}
/* COUNTER WITH SEATING AND STANDING LIMIT WARNINGS */
function ddsSelect() {
if (count === 15) {
message = "you are at full seating capacity"
} else if (count > 16) {
message = "you are over capacity"
} else {
message = ""
}
messageEl.textContent = message
ddsNavEl.style.fontWeight = "bold";
ddsbNavEl.style.fontWeight = "normal";
mciNavEl.style.fontWeight = "normal";
}
function ddsbSelect() {
if (count === 12) {
message = "you are at full seating capacity"
} else if (count > 13) {
message = "you are over capacity"
} else {
message = ""
}
messageEl.textContent = message
ddsbNavEl.style.fontWeight = "bold";
ddsNavEl.style.fontWeight = "normal";
mciNavEl.style.fontWeight = "normal";
}
function mciSelect() {
if (count === 10) {
message = "you are at full seating capacity"
} else if (count > 11) {
message = "you are over capacity"
} else {
message = ""
}
messageEl.textContent = message
mciNavEl.style.fontWeight = "bold";
ddsNavEl.style.fontWeight = "normal";
ddsbNavEl.style.fontWeight = "normal";
}

I didn't include all of your functions in this example, but essentially I think the best way to do this would be to create an object and instantiate it per bus, either based on its type or id of some kind. You mentioned in your example that there were three types of bus... "dds, ddsb, and mci" but essentially by using this technique you could simply instantiate more instances of the object if you needed to setup another bus at some point in the future.
Example below, all of these functions could be setup to accept html elements to update various interface elements. None of that is included because none of it was provided.
let bus = {
passengers: 0,
increase: function() {
this.passengers++;
console.log(this.passengers);
},
decrease: function() {
this.passengers--;
console.log(this.passengers);
},
increaseFive: function() {
this.passengers += 5;
console.log(this.passengers);
},
decreaseFive: function() {
this.passengers -= 5;
console.log(this.passengers);
}
};
// bus types dds, ddsb, mci
let ddsBus = Object.create(bus);
ddsBus.increase();
ddsBus.increaseFive();
let ddsbBus = Object.create(bus);
ddsbBus.increase();
ddsbBus.increaseFive();
ddsbBus.increase();
let mciBus = Object.create(bus);
mciBus.increase();
mciBus.increaseFive();
mciBus.increase();
mciBus.increase();
console.log("dds : " + ddsBus.passengers); //expected value: 6
console.log("ddsb : " + ddsbBus.passengers); //expected value: 7
console.log("mci : " + mciBus.passengers); //expected value: 8

Related

Javascript Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')

I'm trying to make a Farm Clicker game myself with javascript. In other words, as you click the Add Gold button, the player will have more gold and will be able to buy new animals with the gold he has earned. But in my code I come across the following error: script.js:42 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
at addGold (script.js:42:54)
at HTMLButtonElement. (script.js:11:42)
What is this error caused by? I leave the codes below.
// global variables
const myContent = document.getElementById("content");
var gold = 0;
let animals = {};
var goldToAdd = 0;
// global functions
function addGoldButton() {
let myButton = document.createElement("button");
myButton.addEventListener("click", () => addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats * 5; //50=>5 10=>1
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs * 10; //90=>10 9=>1
}
if (animals.cows > 0) {
goldToAdd += animals.cows * 15; //120=>15 8=>1
}
addGold(goldToAdd);
}
addGoldButton();
function addGold(goldToAdd) {
console.trace();
if (gold = null) {
gold = goldToAdd;
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
goldCounter.innerHTML = "Gold: " + gold;
myContent.appendChild(goldCounter);
} else {
gold += goldToAdd;
document.getElementById("goldCounter").innerHTML = "Gold: " + gold;
}
// check for events on current gold level
checkGold();
}
function checkGold() {
if (gold >= 50 && document.getElementById("goatBuyButton") == null) {
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", () => buyAnimal("goat"));
myContent.appendChild(buttonBar);
buttonBar.appendChild(buyButton);
}
if (gold >= 90 && document.getElementById("pigBuyButton") == null) {
let buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.dinnerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", () => buyAnimal("pig"));
buttonBar.appendChild(buyButton);
}
if (gold >= 120 && document.getElementById("cowBuyButton") == null) {
buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Cow (120g)";
buyButton.addEventListener("click", () => buyAnimal("cow"));
buttonBar.appendChild(buyButton);
}
function buyAnimal(animal) {
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id != "itemBar";
myContent.appendChildren(itemBar);
}
switch (animal) {
//do something, don't and forget the break;
case "goat":
if (gold >= 50) {
addGold(-50);
if (animals.goats == null) {
animals.goats = 1;
let myElement = document.createElement("div");
myElement.id = "goats";
myElement.innerHTML = "Goat Quantity: " + animals.goats;
itemBar.appendChild(myElement);
} else {
animals.goats += 1;
document.getElementById("goats").innerHTML = "Goat Quantity: " + animals.goats;
}
}
break;
case "pig":
if (gold >= 90) {
addGold(-90);
if (animals.pigs == null) {
animals.pigs = 1;
let myElement = document.createElement("div");
myElement, id = "pigs";
myElement.innerHTML = "Pig Quantity: " + animals.pigs;
itemBar.appendChild(myElement);
} else {
animals.pigs += 1;
document.getElementById("pigs").innerHTML = "Pig Quantity: " + animals.pigs;
}
}
break;
case "cow":
if (gold >= 120) {
addGold(-120);
if (animals.cows == null) {
animals.cows = 1;
let myElement = document.createElement("div");
myElement.id = "cows";
myElement.innerHTML = "Cow Quantity: " + animals.cows;
itemBar.appendChild(myElement);
} else {
animals.cows += 1;
document.getElementById("cows").innerHTML = "Cow Quantity: " + animals.cows;
}
}
break;
default:
console.log("geen dier gevonden");
}
}
// add elements
// start application
setInterval(passiveGold, 5000);
}
<div id="content"></div>
<!--<script src="script.js"></script> script is referenced right before </body> -->
the element goldCounter is never going to be added to your dom, that's why it says "Cannot set properties of null". At line number 33, in the if statement there is an error.
Replace line 33, this
if (gold = null) {
with
if (gold == 0) {
Hope, it helps!!
The null do not equals to 0, so if the gold contents 0, gold==null will return false and try find the element with goldCounter id (but the easyest way if(!gold))
At the passiveGold function, you do not have to check the animals bigger than 0, because n*0=0, so nothing will happen (it just make your code nicer).
And the buyAnimal function's front: not appendChildren (perhaps you just misspelled it)

Rock Paper Scissors game loop

I'm working on a task to build a Stone,Paper,Scissors Game.
The game is supposed to run in 3 possible modes. best of 3 / best of 5 and endless games.
My code works fine until the point where I reset the game to begin a new game.
For a reason which I can not figure out, it plays multiple instances of my game, each time I call the game() function.
(after the game is over - a reset game button appears and the game mode needs to be reseleted)
I've added the entire project to this https://jsfiddle.net/vydkg3bz/, since I don't manage to pinpoint where the issue is.
I believe, due to all the extra logging I added, that the problem is somewhere in the game() function, as I tried to replace most of the code around it, with the same result.
Maybe someone has a moment to review my code and give me a hint where I should look?
// global variables
var choicesObj = {
Rock: "url('./img/stone.png')",
Paper: "url('./img/paper.png')",
Scissors: "url('./img/scissors.png')",
}
var choices = Object.keys(choicesObj);
var moveAI;
var movePlayer;
var winnerRound;
var winnerGame;
var roundCount = 0;
// actual game
function game(requiredWins) {
console.log("game");
enabler()
var inputs = document.querySelectorAll(".inputButton");
console.log(inputs);
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("click", function() {
movePlayer = this.id
handleClick(movePlayer)
});
}
// checking choice, display choice IMG, call compareChoices function
function handleClick(buttonID) {
console.log("handleClick");
moveAIfunc()
movePlayer = buttonID;
console.log('movePlayer: ' + movePlayer);
console.log('moveAI: ' + moveAI);
document.getElementById("mainImgPlayer").style.backgroundImage = choicesObj[movePlayer];
document.getElementById("mainImgAI").style.backgroundImage = choicesObj[moveAI];
compareChoices(moveAI,movePlayer);
console.log("requiredWins", requiredWins);
gameEnd();
displays();
}
// AI control
function moveAIfunc() {
moveAI = choices[Math.floor(Math.random() * choices.length)]
}
// compare choices
function compareChoices(a, b) {
console.log("compareChoices");
a = choices.indexOf(a);
b = choices.indexOf(b);
console.log("requiredWins", requiredWins);
roundCount++;
if (a == b) {
winnerNone()
return;
}
if (a == choices.length - 1 && b == 0) {
winnerPlayer()
return;
}
if (b == choices.length - 1 && a == 0) {
winnerAI()
return;
}
if (a > b) {
winnerAI()
return;
}
else {
winnerPlayer()
return;
}
}
// game end
function gameEnd() {
console.log("gameEnd");
console.log(requiredWins,winsPlayer,winsAI);
if (winsPlayer == requiredWins) {
console.log(requiredWins,winsPlayer,winsAI);
winnerGame = "Player";
disabler()
createEndButton()
return;
}
if (winsAI == requiredWins) {
console.log(requiredWins,winsPlayer,winsAI);
winnerGame = "AI";
disabler()
createEndButton()
return;
}
}
}```
Your code seems to be pretty complicated. The state of the wins/required wins etc. is not saved adequately in it. For playing you add event listeners per game (click), which is pretty inefficient imho.
I have created a mockup (a minimal reproducable example) for the handling of games, using data attributes to remember the state of a game and event delegation for the handling. Maybe it's useful for you.
Not related, but here's my take on RPS.
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.id === `play`) {
return play(evt.target);
}
if (evt.target.name === `nWins`) {
return reset(evt.target);
}
}
function reset(radio) {
const value = radio === `none`
? Number.MAX_SAFE_INTEGER : +radio.value;
const bttn = document.querySelector(`#play`);
const result = document.querySelector(`#result`);
result.textContent = `(Re)start initiated, click [Play]`;
result.dataset.wins = bttn.dataset.wins = 0;
bttn.dataset.plays = 0;
return bttn.dataset.winsrequired = value;
}
function play(bttn) {
if (+bttn.dataset.winsrequired < 1) {
return document.querySelector(`#result`)
.textContent = `Select best of to start playing ...`;
}
const result = document.querySelector(`#result`);
bttn.dataset.plays = +bttn.dataset.plays + 1;
const won = Math.floor(Math.random() * 2);
const wins = +result.dataset.wins + won;
result.textContent = `${won ? `You win` : `You loose`} (plays: ${
bttn.dataset.plays}, wins ${wins})`;
result.dataset.wins = wins;
if (+bttn.dataset.plays === +bttn.dataset.winsrequired) {
result.textContent = `You won ${wins} of ${
bttn.dataset.winsrequired} games. Choose 'Best of'
to start another game`;
bttn.dataset.plays = bttn.dataset.winsrequired = 0;
result.dataset.wins = 0;
document.querySelectorAll(`[name="nWins"]`)
.forEach(r => r.checked = false);
}
}
Best of
<input type="radio" name="nWins" value="3"> 3
<input type="radio" name="nWins" value="5"> 5
<input type="radio" name="nWins" value="none"> indefinite
<button id="play" data-winsrequired="0" data-plays="0" >Play</button>
<p id="result" data-wins="0"></p>

Onclick event in JS shows results for a second before automatically resetting form

This is a simple quiz/questionnaire, that'll display results of the quiz on submission. It shows the results, but only for about half a second before resetting the page. I would also like for the page to show an alert if the user says they're under 18 when the quiz is submitted; it wouldn't keep them from seeing the answers, but just giving them a message.
function checkAge() {
if(age<18) {
alert("Always make sure you have adult supervision while caring for and handling any venomous arachnid.");
} }
function generateAnswers() {
var choice1score = 0;
var choice2score = 0;
var choice3score = 0;
var choice4score = 0;
}
var chosenAnswers = document.getElementsByTagName('result');
for (i=0; i<chosenAnswers.length; i++) {
if (chosenAnswers[i].checked) {
// add 1 to that choice's score
if (chosenAnswers[i].value == 'choice1') {
choice1score = choice1score + 1;
}
if (chosenAnswers[i].value == 'choice2') {
choice2score = choice2score + 1;
}
if (chosenAnswers[i].value == 'choice3') {
choice3score = choice3score + 1;
}
if (chosenAnswers[i].value == 'choice4') {
choice4score = choice4score + 1;
}
}
}
var maxscore = Math.max(choice1score,choice2score,choice3score,choice4score);
var resultBox = document.getElementById('result');
if (choice1score == maxscore) {
resultBox.innerHTML = "Asian Forest Scorpion"
}
if (choice2score == maxscore) {
resultBox.innerHTML = "Deathstalker Scorpion"
}
if (choice3score == maxscore) {
resultBox.innerHTML = "Desert Hairy Scorpion"
}
if (choice4score == maxscore) {
resultBox.innerHTML = "Emperor Scorpion"
}
}
This is where I put the code:
https://codepen.io/cryceks/pen/vjgzOZ
Use:
event.preventDefault();
This prevents the webpage from reloading and therefore clearing form data

Can't determine reason for NaN output

first time asking a question, long-time lurker. Entry CS student here, first semester working with HTML and JS, and am working on a project that essentially checks the value of some checkboxes, radio buttons, and textboxes, formats some variables based on inputs and values, and outputs that information in a display section. The major issue being, my .js script is resulting in an output in NaN in places I would expect a number and I can't determine as to why. Below is the script, I can amend the html page as well if needed.
But Essentially, in the displayOutput function, the ranging from accessoriesOut to amountOut are giving me a display of NaN and I'm at a loss.
// Declares global variables and their default values.
const STEREO_COST=425.76;
const INTERIOR_COST=987.41;
const NAVIGATION_COST=1741.23;
const STANDARD_FINISH=0;
const PEARLIZED_FINISH=345.72;
const CUSTOM_FINISH =599.99;
const EXCELLENT_CONDITION=1.0;
const GOOD_CONDITION=0.9;
const FAIR_CONDITION=0.8;
const POOR_CONDITION=0.6;
const SALES_TAX_RATE=0.08;
const TRADE="trade";
const ACCESSORIES="accessories";
const SUBTOTAL="subtotal";
const TAX="tax";
const AMOUNT="amount";
const PRICE="price";
const NAME="name";
// Establishes pricing and condition values with the corresponding user inputs.
function pageLoad(){
document.getElementById("stereoDiv").innerHTML += FormatCurrencyText(STEREO_COST);
document.getElementById("interiorDiv").innerHTML += FormatCurrencyText(INTERIOR_COST);
document.getElementById("navigationDiv").innerHTML += FormatCurrencyText(NAVIGATION_COST);
document.getElementById("standardDiv").innerHTML += FormatCurrencyText(STANDARD_FINISH);
document.getElementById("pearlizedDiv").innerHTML += FormatCurrencyText(PEARLIZED_FINISH);
document.getElementById("customDiv").innerHTML += FormatCurrencyText(CUSTOM_FINISH);
document.getElementById("excellentDiv").innerHTML += FormatPercentText(EXCELLENT_CONDITION);
document.getElementById("goodDiv").innerHTML += FormatPercentText(GOOD_CONDITION);
document.getElementById("fairDiv").innerHTML += FormatPercentText(FAIR_CONDITION);
document.getElementById("poorDiv").innerHTML += FormatPercentText(POOR_CONDITION);
}
// Formats money value for output.
function FormatCurrency(amt){
return "$" + amt.toFixed(2); }
// Formats the output and text for currency.
function FormatCurrencyText(amt){
return " (" + FormatCurrency(amt) + ")"; }
// Formats the percent values for display.
function FormatPercentText(pct){
return " (" + (pct * 100).toFixed(2) +"%)"; }
// Determines which trade-in choice is made, and assigns it to and returns a variable.
function getConditionRate() {
var rate;
if (document.getElementById("excellent").checked==true){
rate=EXCELLENT_CONDITION; }
if (document.getElementById("good").checked==true){
rate=GOOD_CONDITION; }
if (document.getElementById("fair").checked==true){
rate=FAIR_CONDITION; }
if (document.getElementById("poor").checked==true){
rate=POOR_CONDITION; }
return rate; }
// Determines which accessories are selected, accumulates and returns a total.
function getAccessoriesTotal() {
var total;
if (document.getElementById("stereo").checked==true){
total += parseFloat(STEREO_COST); }
if (document.getElementById("interior").checked==true){
total += parseFloat(INTERIOR_COST); }
if (document.getElementById("navigation").checked==true){
total += parseFloat(NAVIGATION_COST); }
return total; }
// Determines which finish choice is made, assigns it to a variable for return.
function getFinishAmount(){
var amount;
if (document.getElementById("standard").checked==true){
amount = parseFloat(STANDARD_FINISH); }
if (document.getElementById("pearlized").checked==true){
amount = parseFloat(PEARLIZED_FINISH); }
if (document.getElementById("custom").checked==true){
amount = parseFloat(CUSTOM_FINISH); }
return amount; }
// Determines whether a trade-in was selected, enables/disables controls accordingly.
function EnableTradeIn(){
var isChecked = document.querySelector('[id="tradein"]:checked');
if (isChecked) {
document.getElementById("excellent").disabled=false;
document.getElementById("good").disabled=false;
document.getElementById("fair").disabled=false;
document.getElementById("poor").disabled=false;
document.getElementById("tradeinBox").disabled=false; }
else {
document.getElementById("excellent").disabled=true;
document.getElementById("good").disabled=true;
document.getElementById("fair").disabled=true;
document.getElementById("poor").disabled=true;
document.getElementById("tradeinBox").disabled=true;
document.getElementById("excellent").focus();
document.getElementById("tradeinBox").value=""; }
}
//
function DisplayOutput(accessoriesTotal, tradeinAllowance, subtotal, taxAmount, amountDue, price, name) {
document.getElementById("nameOut").innerHTML=name;
document.getElementById("priceOut").innerHTML=FormatCurrency(price);
document.getElementById("accessoriesOut").innerHTML=FormatCurrency(accessoriesTotal);
document.getElementById("tradeinOut").innerHTML=FormatCurrency(tradeinAllowance);
document.getElementById("subtotalOut").innerHTML=FormatCurrency(subtotal);
document.getElementById("salestaxOut").innerHTML=FormatCurrency(taxAmount);
document.getElementById("amountOut").innerHTML=FormatCurrency(amountDue);
}
function CalculateMain(){
var accessoriesTotal = 0;
var tradeinAllowance = 0;
var subtotal = 0;
var taxAmount = 0;
var amountDue = 0;
var isTradein;
var conditionRate = 0;
var tradeinAmount = 0;
var conditionRate = 0;
var price = document.getElementById("priceBox").value;
var name = document.getElementById("nameBox").value;
//Validate that name is entered
if (name == "" || document.getElementById("nameBox").value==undefined){
document.getElementById("nameError").style.border="1px solid red";
document.getElementById("nameError").innerHTML = "No name entered";
return; }
else{
document.getElementById("nameError").style.border="";
document.getElementById("nameError").innerHTML = ""; }
//Validate price
if (isNaN(price) || price == "" || price < 0){
document.getElementById("priceError").style.border="1px solid red";
document.getElementById("priceError").innerHTML = "Price is not valid";
return; }
else {
price = parseFloat(price);
document.getElementById("priceError").style.border="";
document.getElementById("priceError").innerHTML = "";
}
//Determine if there is a trade-in
isTradein = document.getElementById("tradein").checked;
if (isTradein) {
tradeinAmount = parseFloat(document.getElementById("tradeinBox").value);
conditionRate = getConditionRate(); }
//Validate trade in amount
if (isNaN(tradeinAmount) || tradeinAmount == "" || tradeinAmount < 0) {
document.getElementById("tradeinError").style.border = "1px solid red";
document.getElementById("tradeinError").innerHTML = "Tradein amount is not valid";
return; }
else {
document.getElementById("tradeinError").style.border = "";
document.getElementById("tradeinError").innerHTML = ""; }
//Calculate trade-in allowance (will be 0 if check box is not checked)
tradeinAllowance = parseFloat(tradeinAmount) * parseFloat(conditionRate);
//Validate trade in allowance is not greater than price
if (tradeinAllowance > price){
document.getElementById("tradeinError").style.border="1px solid red";
document.getElementById("tradeinError").innerHTML = "Trade in more than Price";
return; }
else {
document.getElementById("tradeinError").style.border="";
document.getElementById("tradeinError").innerHTML = "";
}
accessoriesTotal = getAccessoriesTotal() + getFinishAmount();
subtotal = price + accessoriesTotal - tradeinAllowance;
taxAmount = subtotal * SALES_TAX_RATE;
amountDue = subtotal + taxAmount;
//Call DisplayOutput
DisplayOutput(parseFloat(accessoriesTotal), parseFloat(tradeinAllowance), parseFloat(subtotal), parseFloat(taxAmount), parseFloat(amountDue), price, name);
}
In the getAccessoriesTotal function, you don't have total defined before trying to add to it. I assume you'd want to default it to 0. (Note: I'd also recommend defaulting amount in getFinishAmount to something).
function getAccessoriesTotal() {
var total = 0;
if (document.getElementById("stereo").checked==true){
total += parseFloat(STEREO_COST); }
if (document.getElementById("interior").checked==true){
total += parseFloat(INTERIOR_COST); }
if (document.getElementById("navigation").checked==true){
total += parseFloat(NAVIGATION_COST); }
return total;
}

javascript countdown with showing milliseconds

I want to do a count down and want to show like format as Minutes:Seconds:Milliseconds. I made a count down with jquery plug-in countdown but it shows just Minutes:Seconds format.
Is there any way to make it right?
Many Thanks!
Hi guys I have developed a code for my self use the following code
counter for 20 seconds
var _STOP =0;
var value=1999;
function settimer()
{
var svalue = value.toString();
if(svalue.length == 3)
svalue = '0'+svalue;
else if(svalue.length == 2)
svalue = '00'+svalue;
else if(svalue.length == 1)
svalue = '000'+svalue;
else if(value == 0)
svalue = '0000';
document.getElementById('cn1').innerHTML = svalue[0];
document.getElementById('cn2').innerHTML = svalue[1];
document.getElementById('cn3').innerHTML = svalue[2];
document.getElementById('cn4').innerHTML = svalue[3];
value--;
if (_STOP==0 && value>=0) setTimeout("settimer();", 10);
}
setTimeout("settimer()", 10);
Try this: http://jsfiddle.net/aamir/TaHtz/76/
HTML:
<div id="timer"></div>
​
JS:
var el = document.getElementById('timer');
var milliSecondsTime = 10000;
var timer;
el.innerHTML = milliSecondsTime/1000;
timer = setInterval(function(){
milliSecondsTime = milliSecondsTime - 1000;
if(milliSecondsTime/1000 == 0) {
clearTimeout(timer);
el.innerHTML = 'BOOOOM';
}
else {
el.innerHTML = milliSecondsTime/1000;
}
},1000);
​
If you want to make your own timer.
read this earlier question
How to create a JQuery Clock / Timer
Try setting the format parameter - http://keith-wood.name/countdownRef.html#format
On further reading, this plugin doesn't do milliseconds. At this point, you either have to edit the actual plugin code or find a new plugin.
I completely agree with #Matt Ball's comment.It may also cause the browser to crash.
Why don't you try this solution instead
jQuery 1 minute countdown with milliseconds and callback
I did it like this (generic counter from N to X (X > N)):
var dynamicCounterAddNewValue = 20;
var currentDynamicUpdater;
function dynamicCounterForValueForControlUpdater(_updaterData) {
_updaterData.from += dynamicCounterAddNewValue;
if (_updaterData.from > _updaterData.to) {
_updaterData.from = _updaterData.to;
}
_updaterData.c.html(_updaterData.from.toString());
if (_updaterData.from < _updaterData.to) {
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
10,
{
c: _updaterData.c,
from: _updaterData.from,
to: _updaterData.to
}
);
}
else {
clearTimeout(currentDynamicUpdater);
}
return;
}
// _c -> jQuery object (div,span)
// _from -> starting number
// _to -> ending number
function dynamicCounterForValueForControl(_c, _from, _to) {
clearTimeout(currentDynamicUpdater);
dynamicCounterForValueForControlUpdater(
{
c: _c,
from: _from,
to: _to
}
);
return;
}
EDIT: Updated version (more flexible - for N elements one after another):
(input element is Array of elements for making them dynamic-counts)
var dynamicCounterTimeout = 10;
var currentDynamicUpdater;
function odcArray(_odca) {
this.odca = _odca;
return;
}
function odc(_c, _from, _to) {
this.c = _c; // $('#control_id')
this.from = _from; // e.g. N
this.to = _to; // e.g. M => (M >= N)
var di = parseInt(_to / 45, 10);
if (di < 1) {
di = 1;
}
this.dynamicInc = di;
return;
}
function dynamicCounterForValueForControlUpdater(_odca) {
if (
_odca.odca === null
||
!_odca.odca.length
) {
clearTimeout(currentDynamicUpdater);
return;
}
var o = _odca.odca[0];
o.from += o.dynamicInc;
if (o.from > o.to) {
o.from = o.to;
_odca.odca.shift(); // Remove first element
}
o.c.html(o.from.toString());
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
dynamicCounterTimeout,
_odca
);
return;
}
function dynamicCounterForValueForControl(_odca) {
clearTimeout(currentDynamicUpdater);
// SETUP all counters to default
for (var i = 0; i < _odca.odca.length; i++) {
_odca.odca[i].c.html(_odca.odca[i].from.toString());
}
dynamicCounterForValueForControlUpdater(
_odca
);
return;
}

Categories