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;
}
Related
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
);
i was wondering how to make a variable go up over time, ive tried to do this -->
var i = 1;
var c = document.getElementById("click");
function workers() {
if (click >= workers*50000)) {
click += -(workers*50000)
click += i++
c.innerHTML = click;
}
}
but it hasnt worked, how do i fix this?
you could do this
let i = 0;
// instead of 2000 insert the frequency of the wanted update (in milliseconds)
const incrementInterval = setInterval(() => i++, 2000)
// when you want it to stop it
clearInterval(incrementInterval)
anyway, i don't really understand how the code supplied with the question has anything to do with it
You have an element and a variable 'click', which tells me you're really not wanting to grow over time per se, but rather grow with every click.
Another difficulty is finding out what you're trying to do with multiplying by 50000. I am assuming you are trying to reset the count after 50000.
One big thing you're missing is the actual association of the click event to your 'click' HTML element. Below, I'm using addEventListener to do that. From there, I'm resetting the counter to '1' if 'i' goes above '5' (I use 5 just to show the reset in a reasonable number of clicks). Then I take the value of 'i' and put it into the innerHTML label of the element that triggered the event.
var i = 1;
document
.getElementById("click")
.addEventListener('click', function(e) {
if (i > 5)
i = 1;
e.target.innerHTML = `click: ${i++}`;
})
<div id='click'>click<div>
Define your question better. What is your goal? What has your code achieved? What result are you getting and how is it different than your expectations? What is 'i' meant to be used for? How does it interact with the function? Why are you multiplying it with 50000? Is workers a separate variable that's globally defined and not shown? Communication is an important skill in this field, and comments are often helpful tools to document your code for others to understand.
I think an alternative answer could be formatted in this way:
let i = 0;
function increment(){
i++;
document.querySelector('h3').textContent = i
}
document.querySelector('button').addEventListener('click',increment)
<button>Click Me</button>
<h3>0</h3>
Here is my javascript loop
for (var i=1; i <= 100; i++)
{
if (i % 15 == 0)
console.log("DuckGoose");
else if (i % 3 == 0)
console.log("Duck");
else if (i % 5 == 0)
console.log("Goose");
else
console.log(i);
}
Im just recently getting into learning html , and java script in my attempts to become a full stack developer by the end of the summer.. Here im trying to use an html button to start/stop this loop and use the function listed below the number 3. Below is what I have so far on the HTML side. Im really hung up and stuck on how to start/stop this loop using this button. Can someone teach me the best way to do this in a beginner way? Still learning. Thanks
<body>
<div>
<button>Click me</button>
</div>
</body>
3
function write (o) {
var el = document.createElement('pre');
el.innerHTML = JSON.stringify(o, undefined, 2);
document.body.appendChild(el);
}
So there is something to be aware of with a for loop, you usually don't stop them with a button click. Once a for loop has started, it will continue to run until 1 of 2 things happen, either the loop's condition evaluates to false, or specifically in code it's told to do something different (either a break or continue statement). So you could have the button click kick off the starting of the loop, but that loop will continue to run until it's done. Using jQuery, it would look something like this.
$(document).on('click', '#duckDuckGoose', function() {
RunDuckDuckGoose();
});
function RunDuckDuckGoose() {
for (var i=1; i <= 100; i++)
{
if (i % 15 === 0)
console.log("DuckGoose");
else if (i % 3 === 0)
console.log("Duck");
else if (i % 5 === 0)
console.log("Goose");
else
console.log(i);
}
}
Now if you REALLY need a button to stop the execution, there are a couple things to keep in mind.
The for loop will go through all 100 elements VERY quickly. So you may want to put something in there to slow down the loops, (or increase the amount of loops) that way you can actually see the stop button work.
In order for the for loop to stop on the button click, the click handler will have to trigger some variable (declared outside of the for loop) that the for loop can look at.
Unfortunately, looping the way I showed you blocks the UI so you can't stop the loop anyway with a button click, so you'd have to look into looping async, see this article for ways to do that.
I hope this helps or at least points you in the right direction. Best of luck on your new journey!
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.
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
});