Increment to a value from 0 in 5 seconds - javascript

I need to increment the value from 0 to 103551 in 5 seconds. Below is the logic I have used. But it's not incrementing to the required value within 5 secs
var counter = 0;
var el = document.getElementById('seconds-counter');
function incrementSeconds() {
counter += 1;
el.innerText = "Processing " + counter + " execution records";
if(counter == 103551) {
console.log(new Date());
}
}
console.log(new Date());
var time = 103551/5000;
var cancel = setInterval(incrementSeconds, time);
HTML
<div id='seconds-counter'> </div>

Your math is a little off. 103551/5000 = 20.7102ms
1000ms = 1s, 5s = 5000ms, 5000/20.7102 = 240 iterations.
The equation you want to solve is 5000/x = numIterations
So x = 5000/numIterations
Note: Most browsers have a minimum number you can set in setInterval(), so you may need to increment by more than 1 each loop to count to 103551 in 5 seconds. Since this is an oddly specific problem I'm going to gues that this might be an assignment so will omit a full solution from this answer. Good luck!

Related

Increment value in time

I am looking to increment the value of "time" with 0.01 each 10 miliseconds until it gets to the desired value. Right now it just increases it instantly to the conditioned value.
var time = 0;
function animate() {
decreaseIncrement = -0.78;
increaseIncrement = 0.78;
if (
(document.getElementById("but5").onclick = function () {
if (time < increaseIncrement) {
do {
time += 0.01;
} while (time < increaseIncrement);
}
})
)
if (
(document.getElementById("but3").onclick = function () {
if (decreaseIncrement < time) {
do {
time -= 0.01;
} while (decreaseIncrement < time);
}
})
)
increaseIncrement = time + increaseIncrement;
decreaseIncrement = time + decreaseIncrement;
}
https://jsfiddle.net/2epqg1wc/1/
You can solve that problem using setInterval which repeatedly runs a task every x milliseconds until you cancel it. Below code reduces the value to 0 in 0.01 steps with a step performed every 10 milliseconds.
var value = 1.0;
var decrement = 0.01;
function decreaseAnimation() {
var interval = setInterval(() => {
value -= decrement;
console.log(value);
if (value <= 0) {
clearInterval(interval);
}
}, 10);
}
decreaseAnimation();
You have 3 options:
requestAnimationFrame (rAF)
setTimeout/setInterval (sTo)
messageChannel
The first 2 options are more straightforward but they will lack the precision, because rAF fires every 17 milliseconds (assuming 60Hz) and sTO will fire at most 4ms after 4 successive recursions. Usually rAF is preferred over sTo because of better reliability in timing of firing these callbacks. Use sTO as a fallback if rAF is not supported.
Here is an implementation from a library for similar purposes:
var rafx = require("rafx");
rafx.async({ //create a ledger object to store values
curr_time:0,
desired:Math.random(),
frames:0
}).animate(function(obj){
//obj is the ledger above
//increment obj.frames here if you want to
return obj;
},).until(function(obj){
obj.frames++;
obj.curr_time = obj.frames * 17 / 10 * 0.01;
return obj.curr_time >= obj.desired;
}).then(function(obj){
console.log("sequence ended with values:" + JSON.stringify(obj));
});
You can copy paste the code above here and test it.
The last option uses MessageChannel to post message between ports, which gives extremely high precision because it is fired at the next event loop. You can combine this with performance.now to determine whether to increment your time or not.
Disclosure: I am the author of the aforementioned lib.

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.

Summing a number recursively and displaying it [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I searched for a solution to this problem quite a bit, but couldn't reach a solution. Would be great if someone can point me in the right direction.
Ok, so suppose there's a number :-
0.001
What I want to do is, add 0.001 (the same number) to it again and again ever second and also display the change dynamically.
So :-
second 1 :- 0.001
second 2:- 0.002
second 3 :- 0.003
This has to keep running for 1 hour and I should be able to see it's value changing dynamically on my web page. How can I achieve this? I did quite a research on using countup.js, but no result. I thought of a solution to use ajax, but this would cause a lot of load.
Whats the best that I can do here?
You can also try this
<div id="display"></div>
var number = 1;
var timer = function(){
number++;
document.getElementById('display').innerHTML = parseFloat(number / 1000);
if(number < 3600){ // 1 hour check
setTimeout(timer,1000);
}
};
timer();
simple with js
var value = 0.001; //value to start
var inc = 0.001; //increment
var end = 0.010; //to test , 1 hour is 3.600
var _interval = setInterval(function() {
document.getElementById('midiv').innerHTML = value;
value += inc;
value = parseFloat(value.toFixed(3));
if (value > end) {
clearInterval(_interval);
}
}, 1000);
<div id="midiv">
</div>
Here is an example using rxjs
var interval = 1000;
var totrun = 60*1000
var v = 0
const source = Rx.Observable
.interval(interval)
.takeUntil(Rx.Observable.timer(totrun));
const subscription = source.subscribe(
t => {
v=v+0.001
$('#v').html(v);
},
err => console.log('Error: ' + err),
() => console.log('Completed'));
Is this what you want?
feel free to play with it
var c = 0.000;
var count = document.getElementById('count');
count.innerHTML = c;
// Creates the interval with the name interval
var interval = setInterval(function() {
c += 0.001
count.innerHTML = c;
// Its possible that you will see 0.00300000000007 artifacts
// You can fix it by converting it to a string and showing only a part
// count.innerHTML = ("" + c).substring(0, 5);
}, 100) // 1/10 sec for demo
// Clear the interval after one hour
setTimeout(function() {
clearInterval(interval)
}, 1000) // one second for demo
counter: <span id="count"></span>
var interval = setInterval(function(){
var old = parseFloat($(".number").html());
var newValue = old + 0.001;
$(".number").html(newValue);
}, 1000);
// this clears the interval loop from firing after 1 hour
setTimeout(function(){
clearInterval(interval);
}, 3600000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="number">0.001</div>
That should do the trick

Javascript countdown then count-up from a prompted variable?

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

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!

Categories