Javascript countdown then count-up from a prompted variable? - javascript

Please Help! I'm new to Javascript, so there's probably an easier solution to this. Basically, I need it to prompt for a number and then count down from that number to zero. Once it reaches zero, I need it to count-up and stop at the same prompted number.
I got it to count down at first, then I completely butchered it, I have no clue what to do.
<script type="text/javascript">
// get number from user
var startNum = parseInt(prompt("Input a number to start counting down from.",""));
var counter = setInterval(timer, 1000);
console.log(startNum);
function timer() {
startNum--; // reduce number by 1
console.log(startNum);
if (startNum <= 0) {
clearInterval(counter);
}
}
var counter = setInterval(timer2, 1000);
var endNum = 0
function timer2() {
console.log(endNum)
endNum++; // add number by 1
console.log(endNum);
if (endNum >= startNum) {
clearInterval(counter);
}
}
</script>

You've got a couple issues here. the first one was pointed out by Rob in the comments. You're running both functions at the same time.
The other issue you have is that you're never storing the number. You're just subtracting and adding to nothing essentially.
So -
<script type="text/javascript">
// get number from user
var startNum = parseInt(prompt("Input a number to start counting down from.",""));
var currentNum = startNum;
var counter = setInterval(timer, 1000);
function timer() {
console.log(currentNum);
currentNum -= 1; // reduce number by 1
console.log(currentNum);
if (currentNum == 0) {
clearInterval(counter);
counter = setInterval(timer2, 1000);
}
}
function timer2() {
console.log(currentNum)
currentNum += 1; // add number by 1
console.log(currentNum);
if (currentNum == startNum) {
clearInterval(counter);
}
}
</script>
Something like this should do the trick. Basically creating another variable to hold your start number and consider that the current number and the value that is going to change.
here's a fiddle - http://jsfiddle.net/w5FM6/
cheers

Related

How to investigate why the setTimeout function is not working in my code?

My code works and all values are true so that it should be running, but it does not.
I have tried localizing the variables, changing the timing, and rearranging functions and nametags.
auto1();
var autocount = 0;
var autotrue = 0;
function auto1(){
setTimeout(function() {
while(autotrue==1){
money = money + autocount;
setText("money_display",money);
}
}, 1000);
onEvent("auto1", "click", function(){
if(money >= 10){autotrue = 1;
money = money - 10;
autocount = autocount+1;
console.log("You now have " + autocount + " J$ per second");
} else {
console.log("you have insufficient J$ for this purchase");
}
});
}
I expect it to add 1 to my money variable every 1000 ms. But it does nothing to the money variable
There are a few problems here:
setTimeout only runs once, at the end of 1000 ms. In this case, when it runs, you're going to enter an infinite loop because autotrue is never getting set true. It's still 0 and you're adding it to money and money will never get over 10 because 0+0=0.
If you wanted to repeatedly add to money every 1000 ms, you would use setInterval, without any loop inside. That will call your function over and over every 1000 ms.
There were several issues with your code:
the money variable was not defined
The while loop inside the timer would make the browser freeze
the timeout should be an interval instead
autotrue should probably be a boolean
I faked the setText() function and changed onEvent() to addEventListener() for the sake of a working example:
auto1();
var autocount = 0;
var autotrue = false;
var money = 10;
function auto1() {
autoAddInterval = setInterval(function() {
if (autotrue) {
money = money + autocount;
setText("money_display", money);
}
}, 1000);
document.getElementById('auto1').addEventListener("click", function() {
if (money >= 10) {
autotrue = true;
money = money - 10;
autocount = autocount + 1;
console.log("You now have " + autocount + " J$ per second");
} else {
console.log("you have insufficient J$ for this purchase");
}
});
}
function setText(id, value) {
document.getElementById(id).innerText = value + ' J$';
}
setText("money_display", money);
balance: <span id="money_display">0 J$</span><br>
<button id="auto1">purchase +1 J$ per second</button>
You call auto1 before the variables autocount and autotrue were initialized to 0, therefore they are still undefined and will break your calculations. You should call that function after initializing all the variables.
Additionally while(autotrue==1){ looks as if it is infinite, as there is nothing changing autotrue. Infinite loops are always bad.
Take this out and you will see that the timer works.
while(autotrue==1){
money = money + autocount;
setText("money_display",money);
Your problem is that you are not setting the autotrue var to 1 anywhere.

Point out errors in a JavaScript Loop

What's wrong with this function? I want to add 1 to c_count until it reaches 100
<script type="text/javascript"> var result = cMat(0); function cMat (c_count) { var limit = 100; match = 1; while (c_count != limit) c_count ++ match; if (c_count == 95) { c_count = 10; } } return (c_count) } </script>
I want to add 1 to c_count until it reaches 100
You're resetting c_count to 10 every time it reaches the value of 95, so it's never reaching your limit. Your match variable doesn't seem to be used, so it can be removed. One thing to check is where the value of c_count is in relation to 100. If it's greater than 100, you need to decrement the value instead of incrementing it.
var result = cMat(0);
function cMat (c_count) {
var limit = 100;
while (c_count != limit)
if(c_count < limit) {
c_count++;
} else { // Implied that it's greater than the limit at this point
c_count--;
}
}
return c_count;
}

Creating Javascript countdown from currentvalue to targetvalue and change numbers every sec

currentValue = 708295;
targetValue = 0;
function count() {
if (currentValue > targetValue) {
currentValue -= 1
} else if (currentValue < targetValue) {
currentValue += 1
}
document.getElementById('timeTo').innerHTML =
'Total wordcount:'+ currentValue.toString();
changeTime = 1000;
if (Math.abs(currentValue - targetValue) <0) {
changeTime = 1000 - Math.abs(currentValue - targetValue);
}
setTimeout(count,changeTime/1);
}
count()
<h1 id="timeTo">Starting</h1>
any help will be very useful, i m trying to learn javascricpt and i want to create count down.
I want number to go down every sec but so far i have created the function to count the number but its counting too fast
ANy help or any suggestions
Thanks
setTimeout second argument is miliseconds value, it should be set to 1000 if you want to tick every second.

How to grow number smoothly from 0 to 5,000,000

This is probably basic math that I don't seem to remember.
I'm trying to get from 0 to 5,000,000 in 10 seconds while having all the numbers ticking. I don't have to have the number reach exactly 5,000,000 because I can just do a conditional for it to stop when it's over.
Right now I have this:
count+= 123456
if (count > 5000000) {
count = 5000000;
}
It gives the sense of number moving you know? But It really starts off too high. I wanted to gradually climb up.
You could do something like this:
function timedCounter(finalValue, seconds, callback){
var startTime = (new Date).getTime();
var milliseconds = seconds*1000;
(function update(){
var currentTime = (new Date).getTime();
var value = finalValue*(currentTime - startTime)/milliseconds;
if(value >= finalValue)
value = finalValue;
else
setTimeout(update, 0);
callback && callback(value);
})();
}
timedCounter(5000000, 10, function(value){
// Do something with value
});
Demo
Note that with a number as big as 5000000 you won't see the last couple digits change. You would only see that with a small number like 5000. You could fix that; perhaps by adding in some randomness:
value += Math.floor(Math.random()*(finalValue/10000 + 1));
Demo with randomness
You can tween:
import fl.transitions.Tween;
import fl.transitions.easing.Regular;
var count = 0;
var tween:Tween = new Tween(this, "count", Regular.easeInOut,0,5000000,10, true);
This will tween you variable count from 0 to 5000000 in 10 seconds. Read about these classes if you want to expand on this code.
Tween
TweenEvent
Good luck!

Why does my JavaScript Prime Number-Generator not work?

The aim of this program is to list all the prime numbers from 1 up.
I am a complete novice. I began writing this in C++ (unsuccessfully) and translated to this (JS)
I am aware of some problems but don't know how to solve them:
handling global variables,
writing replaces,
no timeout before writing, etc.
is it important that i use an external JS file?
In summary, how do i make this work?
<!doctype html>
<html>
<head>
<script>
var number = 3; //to be run through the prime test
var prime = [2]; //numbers found to be prime
var found = 1; //counter for primes found
var runs = 0; //counter for times number has been tested
//numbers are tested against all smaller found primes
function test()
{
window.scroll(0,document.height); //automatically view the latest prime
var line = document.createElement("div");
while(runs < found && (prime[runs] < (number / 2))) //has number passed all tests
{
if(number % prime[runs] !== 0) //is number divisible by smaller prime
{
runs = runs + 1; //number passed a test
}
else //number is not prime
{
number = number + 1; //next number generated
runs = 0; //reset test counter for next number
setTimeout(test, 100); //start running next number tests
}
} //number passed all tests
line.innerHTML = number; //prime number displayed
document.body.appendChild(line);
prime[found] = number; //prime number saved for testing
found = found + 1; //counter for found is increased
number = number + 1; //next number generated
runs = 0; //reset test counter for next number
setTimeout(test, 100); //start running next number tests
}
</script>
</head>
<body>
<form>
<input type="button" onclick="test()">
</form>
</body>
</html>
On the mathematical side,
var prime = [1];
1 isn't a prime, and since 1 divides every number,
while (runs < found) //has number passed all tests
{
if (number % prime[runs] !== 0) //is number divisible by smaller prime
{
runs = runs + 1; //number passed a test
}
else //number failed a test
{
number = number + 1; //next number generated
runs = 0; //reset test counter for next number
setTimeout(test, 1000); //start running next number tests
}
} //number passed all tests
always enters the else branch for runs = 0.
You can start with var prime = [2]; or with var prime = []; and var found = 0;.
A few things to note:
for (runs < found)
You appear to want a while loop here. for loops cannot consist just of a condition.
document.writeln() cannot be used after the document has finished loading and has closed. Using them after this will re-open the document, resetting it to blank.
To modify the DOM after this, you'll need to use innerHTML or document.createElement() and element.appendChild().
var line = document.createElement('div');
line.innerHTML = number;
document.body.appendChild(line);
To avoid infinite recursion and give the UI thread a chance to update the display of the page, you can use a timer when calling test again:
setTimeout(test, 100);

Categories