Is it possible to have two Else conditions run simultaneously? - javascript

I am creating a game that when the play button is clicked, the timer starts. When my time is 0 I want to the paragraph with #timeline to be replaced with different text, which works perfectly. However how can I simultaneously add a .class to the replacement text so I can style "Your time is up!" differently when it is displayed.
var secondsLeft = 20;
function startTimer(){
setInterval(myTimer, 1000);
}
function myTimer(){
if(secondsLeft!=0){
document.getElementById("time").innerHTML = secondsLeft-=1;
} else {
document.getElementById("timeLine").innerHTML = "Your time is up!";
}
}

No. You cannot. With any programming language, you need to follow the basics of an if statement. If statements can have numerous else conditions, but only one condition will be met. This is how control flow is accomplished. It will keep going down the list until one condition is met. In your case, the first condition with "time" is the proper code that would be run.
As far as styling goes for time === 0, you should try putting both in the same else condition and see if that is what you are looking for.

Related

How to change an objects properties right after a condition is met?

I am trying to make a button go from .disabled = true to .disabled = false. I am making a Yahtzee clone for fun, and you have to choose a score to take on your third roll, and then after that the button will be unlocked and you can roll again. Here's what I had, but it crashes. I wanted to make a while statement until a score is selected. ptsss is the amount of scores that have been selected. (i.e. third roll should equal 1 score entered)
if(rollcount == 3){
while (ptsss * 3 < rollcount){
document.getElementById("rollbutton").disabled = true;
if (ptsss * 3 == rollcount){
document.getElementById("rollbutton").disabled = false;
break;
}
}
}
}
Try removing the while loop and (possibly) rewrite the code as a function to enable/disable the roll button as required. E.G.
function checkRollButton( rollcount, ptsss) {
if(rollcount == 3) {
document.getElementById("rollbutton").disabled = ptsss != 1;
}
}
Then call (or inline the code for) checkRollbutton in event handlers that update rollcount and/or ptsss.
As commented, the value of ptsss cannot be changed by other code while the while loop is running, because JavaScript is single threaded.
I've modified the statement that enables/disables the roll button according to my understanding of the design, please check it before use.
Loops in JavaScript are not like loops in some other languages.
If the condition in the loop is not being modified within the loop itself, it won't be modified (unless possibly it's happening inside an asynchronous function).
Also you shouldn't constantly use the getElement in a loop anyways.
The way to achieve the general functionality of what a while loop is in other languages, in JavaScript, is to use an interval.
So based on that your updated code can look something like this (not sure where the first if statement is being called from so I took it out, also the nested if statement would have never been called because it only takes effect if it's condition is false, so I changed that as well):
var roll=document.getElementById("rollbutton")//make sure this is called after that element has loaded
var inter=setInterval(function(){
if (ptsss * 3 == rollcount){
roll.disabled = false;
clearInterval(inter)
//Similar to break in while loop, can restart interval later after this
}
if (ptsss * 3 < rollcount){
roll.disabled = true;
}
}
},1000/30//30 FPS
);

Why will my button not advance to the next question?

I am a new developer and this is my first question. I am trying to make a multiple choice quiz for an assignment. I am stuck on making the NEXT button move to the next question. I think the rest of the JS file is correct...
Right now the clickNext doesn't do anything, so I need to do the following
check if the time expired (line 39)
did the user answer the question in the allotted time (line 40)
if no, try again and the clock will start over (line 60-70)
if yes, then store the answer selected - I think this part is tripping me up and I am not sure what to use here
check if the selected answer is correct (line 50-57)
if the answer is correct, move to the next question (line 52-53)
if the answer is wrong, alert "Please try again" (line 55-56)
I have tried to return the answer, the addEventListener, putting the checkAnswer function in the clickNext function
var indexQuestion = 0; // Current index of question we are on
var timer = 0; // A clock that goes up by 1 every second
var timeLastSubmit = 0; // the time we last submitted an answer
var timeExpired = false; // Did time expire for current question?
// number of seconds to wait for each question
var WAIT_TIME = 30;
// all questions to be used on the website
var QUESTIONS = [
{
"question":"Which city is the capital of Ontario?",
"choices":["New York","Toronto","Berlin","Kuala Lumpur"],
"answer":1
},
{
"question":"Which city is the capital of Canada?",
"choices":["New York","Toronto","Ottawa","Vancouver"],
"answer":2
},
{
"question":"Which continent does the south pole reside?",
"choices":["Africa","Antarctica","Asia","Australia","Europe","North America","South America"],
"answer":1
},
];
function loadApplication() {
loadQuestion(indexQuestion); // load the first question into the web page
// update the timer every second and check if question has been answered yet
setInterval(function(){
timer++;
checkExpirationTime();
},1000);
}
function clickNext() {
// make sure that the user has answered the question before the time has expired
timeLastSubmit = timer;
checkExpirationTime();
// Get the answer from drop down
var selectedIndexAnswer = getElementById('choices');
return selectedIndexAnswer;
// Get the anwer from the array
var answer = QUESTIONS[indexQuestion].choices[i];
checkAnswer();
};
function checkAnswer(){
// Compare answer. Only if correct, do you move onto next question - if(answer == QUESTIONS[indexQuestion].answer)
if(selectedIndexAnswer == answer) {
nextQuestion();
}
else {
alert('Please try again.');
}
}
function checkExpirationTime() {
// check the time, once the clock has reached 30 seconds do not move to the next quesiton
if(timer - timeLastSubmit < WAIT_TIME && !timeExpired){
document.getElementById("seconds").innerHTML = WAIT_TIME;
}
else{
timeExpired = true;
alert('Please try again.');
clearInterval(timeExpired);
}
}
function nextQuestion() {
// advance to the next question, until the there are no more questions
if(indexQuestion<QUESTIONS.length-1)
{
indexQuestion++;
loadQuestion(indexQuestion);
}
}
function loadQuestion(indexQuestion){
// grab the question
document.getElementById("question").textContent = QUESTIONS[indexQuestion].question;
// build the html string for select menu
var choices = "";
var i=0;
//loop through the choices
while(i<QUESTIONS[indexQuestion].choices.length){
// create a string of <option>answer</option><option>answer</option><option>answer</option>... and load it into the choices variable
choices += "<option>" + QUESTIONS[indexQuestion].choices[i] +"</option>";
i++;
}
document.getElementById("choices").innerHTML = choices;
}
// When the DOM is ready, run the function loadApplication();
document.addEventListener("DOMContentLoaded",loadApplication);
Right now the program does not advance to the next question, but it just stays on the first question.
To answer your first question
I am stuck on making the NEXT button move to the next question
For this you need to add click event listener to next button.
document.getElementById("btnNext").addEventListener("click",clickNext)
And the next part
I think the rest of the JS file is correct.
Almost.. You need to make a few corrections here and there.
I made some edits to the pen and is available here.
https://codepen.io/nithinthampi/pen/Yzzqqae
As, you are a learner, I would suggest not to copy it. Even the codepen I shared is not complete, but should help you to move on.
Going through your pens, here are the following issues I found with your code:
Misuse of return statements. You added a return statement in the second line of your function causing the rest of it to be completely ignored.
function clickNext() {
// make sure that the user has answered the question before the time has expired
timeLastSubmit = timer;
checkExpirationTime();
// Get the answer from drop down
var selectedIndexAnswer = getElementById('choices');
Here --> return selectedIndexAnswer;
// Get the anwer from the array
var answer = QUESTIONS[indexQuestion].choices[i];
checkAnswer();
}
onclick not added to your "Next" button, neither a addEventListener in your script was. As a result, clicking the "Next" button had no effect on your app, at all.
<button id="btnNext">Next</button>
Scoping problems. In JavaScript, when you define a variable within a scope, that variable can never be accessed from outside that very scope. Meaning defining a variable inside a function (like in your case) will not make it available in another completely separate function (unless you pass it as a parameter in some way). I'd recommend researching a bit more about JavaScript scopes to get a better of idea of how it works.
All 3 issues have been fixed in a new pen I've created for you to take a look at: https://codepen.io/MMortaga/pen/PooNNYE?editors=1010
However you might need to play a bit more with your timer, so see if you can fix it :P
Take the time to review all the changes I've mentioned and if you still face any issues just comment below, I'd be glad to help.

For Loop Not working with inner html Javascript

I am writing a code in java script to display a countdown from 10 to 0. Loop is working for alert but when i use document.getElementById the loop doesn't work and it shows 0. Here's My Code
heading is the id of h1
function msg(z)
{
try
{
for(var i=0;i<=10;i++)
{
var seconds=z-i;
document.getElementById("heading").innerHTML="Select T
The Multiples of 2 in"+" "+seconds+" "+"seconds";
}
}
catch(e)
{
document.write(e);
}
Have you use debug tools to verify if the problem is in the loop? You are not waiting any second in each loop iteration, so youll see the end result as it will execute in much less than a second, so youll see 0 (the final iteration)
Take a look at this post Javascript Second Counter as is basically the same as you are trying to do.
Hope this helps
I Changed My function to this and it's working fine.
P.S:- I Have Not added any constraints yet!
function msg(){
function timer()
{
seconds -=1;
document.getElementById("heading").innerHTML="Select The Multiples of 2 in"+" "+seconds+" "+"seconds";
}
var cancel=setInterval(timer,1000);
setTimeout(function(){if(cout<10){alert("Time Over You Lose!");}else{alert("You Have Completed Level 1");}},10000);
}

Why does the Countdown stuck at "1"?

var count=6
var counter=setInterval(timer, 1000);
function timer(){
count=count-1;
if (count === 0){
requestAnimationFrame(repeat);
clearInterval(counter);
return;
}
var countdown = createEntity($('<div id="countd"><p id="countp"></p></div>'));
game.add(countdown);
document.getElementById("countp").innerHTML=count;
}
This is my approach to the Countdown. I'm coding a Game. First of all it shows a Countdown... But why does it stuck at "1"? And if I'm playing it still staying "1" over the display.
My idea was, clearInterval(Counter) but it doesn't work. Are there any other approches?
The problem with your code is that you:
decrement the variable
test if it is zero and if so you return from the loop.
In all other cases you update the div tag.
In other words: if the counter is zero you do not update the div-tag, and therefor the last displayed value is 1
Assuming that the problem you are describing is the only problem with your code, you could change it to something like this:
function timer() {
var countdown = createEntity($('<div id="countd"><p id="countp"></p></div>'));
game.add(countdown);
count -= 1;
document.getElementById("countp").innerHTML=count;
if (count === 0) {
requestAnimationFrame(repeat);
clearInterval(counter);
}
}
I basically just moved the if-statement to after the field is updated. I have not tested the code, but if you get the idea of what to change.
I am however curious if you really want to call createEntity and game.add(countdown) on every timer-invocation. In most cases you want to create the tag before you call the timer-function, and just update the value. But maybe you are doing some animation and therefor need individual tags for each value, so it isn't necessarily wrong to do it that way.
If it is a display only issue (which I am guessing it is), then the update to HTML should be made before you return from the function when the count is 0. In case the counter goes to 0, you are not updating the display.
if (count === 0){
//assuming repeat is a variable defined somewhere in the rest of your code
requestAnimationFrame(repeat);
document.getElementById("countp").innerHTML=count;
clearInterval(counter);
return;
}

Making a total number count appear to increase

Basically I have a class counting system that displays the number of classes and displays them in a span element. Below is the code:
$.get('other.html', function(data) {
$('#total').html($('.doc', data).length);
});
This works perfectly, however I'd like a way to have the numbers increasing one by one since the span element contains 0 when the page loads. Here's an example (the numbers increasing on here).
For this I have tried setTimeout and despite this not working anyway, I released it would simply delay the function and then display the end number. I have heard of periodical or something similar being used but could not find this in the example source code.
I am really sorry for more poor phrasing. If you have no idea what I mean then just ask and I'll try rephrase or find a better example.
The key is the function which increases the number should set a setTimeout to call itself, before termination. This way it will always be called again. If you want the option to stop the incrementing, you can add a global variable, and the function will only set a new timeout when that variable is true.
Example:
var doIncrement = true;
var numberToIncrement = 0;
function increment {
numberToIncrement++;
$('#mySpan').text(numberToIncrement);
if (doIncrement) {
setTimeout(increment, 1000);
}
}
You could use the setInterval function that allows you to run code at some time intervals. clearInterval allows to stop the task.
http://jsfiddle.net/d52Pw/
var $totalEl = $('#total');
$.get('other.html', function(data) {
var len = $('.doc', data).length,
count = 0,
int = setInterval(function () {
if (++count === len) {
//when we reach len, we stop the task
clearInterval(int);
}
$totalEl.html(count);
}, 500); //run every 1/2 sec
});

Categories

Resources