How to make a JS Counter & Reset? - javascript

I am trying to make a JS counter to reach a random number and reset it self once it reaches the number and repeat again in 5 seconds.
For example: Random Number is 0.05.
0.00 > 0.01 > 0.02 > 0.03 > 0.04 > 0.05 > 0.00
<div id="current">0</div>
JS
var randomNum = Math.random();
if ( current <= randomNum ) {
for (current = 0; current < randomNum; current+=0.01) {
setInterval(function(){
current += .01;
},1000); } }
else {
current = 0;
}

You could use a closure over the variables and make a check inside of the callback, if greater then the wanted result.
This proposal uses setInterval for counting and setTimeout for the waiting time of 5 sec and the restarting with a new random value.
function startInterval() {
var randomNum = Math.floor(Math.random() * 8) + 2,
current = 0,
interval = setInterval(function() {
current += .01;
if (current > randomNum / 100) {
current = 0;
clearInterval(interval);
setTimeout(startInterval, 5000);
}
document.getElementById('current').innerHTML = current.toFixed(2);
}, 1000);
}
startInterval();
<div id="current">0</div>

Keep a counter variable outside of the loop and then simply clear it, when the desired value is reached.
var randomNum = Math.random() * 25;
var currentValue = 0;
var counter;
counter = setInterval(function() {
if (currentValue < randomNum) {
//Carefull with "0.1" as JavaScript doesn't like it!
currentValue = (currentValue * 10 + 1) / 10
}
if (currentValue > randomNum) {
currentValue = randomNum;
clearInterval(counter);
}
console.log(currentValue, '/', randomNum)
}, 1000 / 60)

Related

The if statement wont read vairables

I cant get my if statements to run it will only run the count down portion but the specifics like when it gets to 5 and 0 it just wont run those extra if statements.
function Countdown()
{
var currTime = 10;
var i = 10;
while (i>=0) {
if (currTime == 5)
{
setTimeout(function () {
document.getElementById("counter").innerHTML = "Warning Less than ½ way to launch, time left = " + currTime;
currTime = currTime - 1;
}, 1000 * i);
i -= 1;
}
if (currTime == 0)
{
document.getElementById("counter").innerHTML = "Blast OFF";
}
else
{
setTimeout(function () {
document.getElementById("counter").innerHTML = "the time left is " + currTime;
currTime = currTime - 1;
}, 1000 * i);
i -= 1; /* same as i = i-1 */
}
};
}
Actually your while loop execute the currTime 11 times here. The main issue is here you are using interval of 1 sec or 1 sec+ etc, but your loop runs very fast in ms of 100 or 500 which excecute currTime very fast. That's the issue here. I hope you got the issue.

How to check if a variable value is increasing or decreasing and show the number with what it increased or decreased

This is a dumb question, And I can't believe I asked for a solution, Well now that I am pretty good I answered it. So, Firstly I create the variable number then I add two properties to it's prototype called oldValue and randomize then I set randomize to a random decimal number between 0 and 1 using Math.random(), I store the value of the number variable before any further changes, In the property I added to the prototype called oldValue, After that I check if the randomize is less than 0.5 or more than 0.5 if less then I decrement a random number between 50-100 else I increment with a number between 50-100, At last I console.log() the changes.
let number = 0;
number.__proto__.oldValue = number;
number.__proto__.randomize = 0;
let interval = setInterval(() => {
number.__proto__.randomize = Math.random();
let randomNumber = Math.floor(Math.random() * (100 - 50) + 50);
number.__proto__.oldValue = number;
if (number.randomize > 0.5) number += randomNumber;
else number -= randomNumber;
console.log((number - number.oldValue) < 0 ? `decrement: ${number} ${number.oldValue}` : `increment: ${number} ${number.oldValue}`);
}, 100)
You can store the delta in a variable. Additionally, to generate a random boolean, you only need to check if Math.random() is greater than 0.5.
var number = 0;
setInterval(() => {
let delta = Math.floor(Math.random() * 100) * (Math.random() > .5 ? 1 : -1);
console.log('Delta:', delta);
number += delta;
}, 100)
When you are creating random number you can store it. Math.floor(Math.random() * 100)
Like this:
var number = 0;
var randomize = 0;
setInterval(() => {
randomize = 0;
randomize += Math.floor(Math.random() * 100);
if (randomize > 50) {
let newRandomise = Math.floor(Math.random() * 100);
number += newRandomise
console.log("increased by", newRandomise)
}
else {
console.log("deccreased by", randomize)
number -= Math.floor(Math.random() * 100)
}
}, 100)
Just add some console.log s that will help you
var number = 0;
var randomize = 0;
setInterval(() => {
randomize = 0;
randomize += Math.floor(Math.random() * 100);
if (randomize > 50) {
const incrementer = Math.floor(Math.random() * 100);
console.log('Increased by', incrementer);
number += incrementer;
}
else {
const decrementer = Math.floor(Math.random() * 100);
console.log('Decreased by', decrementer);
number -= decrementer;
}
}, 100)

Why is my counter function not incrementing?

Basically I wanted to make a countdown with javascript, following my logic the code below should work, but for unknown reason it is not working. Could someone help me to figure out what's wrong with the code? It's kind of annoying.
function startCounter(time)
{
var counter= document.getElementById("counter").innerHTML;
var min=0;
setTimeout(function()
{
for(i = 0; i < time; i++)
{
document.getElementById("counter").innerHTML = min+ ":" +i;
if(i == 59) {
min++;
i = 0
document.getElementById("counter").innerHTML = min+ ":" +i;
}
}
}, 1000)
};
startCounter(89);
<p id="counter">0:00</p>
You are creating an infinite loop.
You are wrapping this part:
if(i == 59) {
min++;
i = 0
document.getElementById("counter").innerHTML = min+ ":" +i;
}
in a for loop that uses i as a limiter. Each time the i reaches 59, you are resetting it back to 0, and the loop continues.
// Add your code here
function startCounter(time)
{
var counter= document.getElementById("counter").innerHTML;
var min = parseInt(time / 60);
var seconds = time % 60;
setInterval(function()
{
seconds++;
document.getElementById("counter").innerHTML = min+ ":" +seconds;
if(seconds == 60) {
min++;
seconds = 0
document.getElementById("counter").innerHTML = min+ ":" +seconds;
}
}, 1000)
};
console.log("Start");
startCounter(89);
<p id="counter">
</p>
The issue is with this line:
for(i=0;i<time;i++) {
You have an infinite loop if your time is > 59, because of this line:
if(i==59){
//snip
i=0
}
Since your function is never finishing setTimeout is never finishing and the browser doesn't appear to be updating your element.
Don't set i back to zero, so your for(true) condition ist always true and your loop can't stop.
function startCounter(time)
{
var counter= document.getElementById("counter").innerHTML;
var min=0;
setTimeout(function()
{
for(i = 0; i < time; i++)
{
document.getElementById("counter").innerHTML = min+ ":" +i;
if(i == 59) {
min++;
document.getElementById("counter").innerHTML = min+ ":" +i;
}
}
}, 1000)
};
startCounter(89);
<p id="counter">0:00</p>
var timer;
var i = 0;
var counter = document.getElementById("counter");
var min = 0;
var targetTime = 5;
function startCounter(){
if(min < targetTime){
if(i == 59){
min++;
i = "00";
} else {
i++;
if (i < 10) {
i = "0"+i;
}
}
counter.innerHTML = min + ":" + i;
} else {
clearInterval(timer);
}
}
timer = setInterval(startCounter, 1000);
<p id="counter"></p>
You have a couple of problems... you seem to be trying to iterate seconds inside the callback that will be executed once every second.
Even if you fixed that code, you're going to have a problem with the fact that setTimeout does not execute exactly at the specified value. It fires whenever the thread can queue the task > the time scheduled. So your timer is going to drift over it's duration.
I'd recommend the below approach. Using a requestAnimationFrame loop (you could also use an interval) check the difference in the JavaScript clock between the time you started and now and then print the difference.
var firstTime;
function startTimer(){
firstTime = Date.now();
runTimer();
}
function runTimer(){
var diff = Date.now() - firstTime;//value in milliseconds since the timer started.
var sec = Math.floor((diff/1000)) % 60;//constrain to seconds
var min = Math.floor(diff/(1000 * 60));//minutes
document.getElementById('timer').innerHTML = min + ":"+(String(sec)).padStart(2,"0");
requestAnimationFrame(runTimer);
}
startTimer();
<div id="timer">0:00</div>
You have a couple options that would work. Calling the startCounter again from inside your setTimeout function or my favourite way is window.setInterval.
var p = document.getElementById("count");
function startTimer(time){
var num = 0; // the increment number
var intervalId = window.setInterval(function(){
num += 1; // increment the number
if(num == time){
window.clearInterval(intervalId);
// you can run your callback here after the timer reached your goal
startTimer(num + 1); // this just adds a second and restarts the timer as a example
}
p.innerText = num;
}, 1000);
}
// Start the timer here
startTimer(10);
<p id="count"></p>

Simulate app loading with HTML 5 progress bar

I am aiming for a loading progress bar that fluctuates in speed as it goes from 0 to 100%. I would like some variety in the way it loads to give the appearance of loading my app. The following code sorta gets me there, but just not with the variety I was looking for.
Any suggestions on how to improve upon or completely reconstruct this?
UPDATE:
I have altered the code myself to achieve what I'm looking for.
Here's a fiddle: JSFIDDLE
var counter = 0; var factor = 1;
var timer = setInterval(function () { // timer function for progress bar
counter = counter + factor;
$('.progressbar').val(counter);
if (counter >= 10 && counter <= 59) {
damping = Math.floor(Math.random() * (300 - 25)) + 6;
factor = Math.max((100 - counter) / damping, '0.5');
} else if (counter >= 60 && counter < 100) {
damping = Math.floor(Math.random() * (50 - 25)) + 3;
factor = Math.max((100 - counter) / damping, '0.5');
} else if (counter > 100) {
clearInterval(timer);
};
}, 30);

Making a number change gradually rather than immediately

I would like to change a number from n1 to n2 gradually that is if n1 is 5 & n2 is 10 then I want it to change like 6, 7, 8, 9, 10 instead of changing abruptly from 5 to 10
Here is the part;
var interval = setInterval(gMoneyU1, 1000);
function gMoneyU1()
{
var calc = 5 * U1Amount;
Money += calc;
document.getElementById('money').innerHTML=Money + "$";
}
I think you should use setTimeout to achieve this, I am writing a more general code but you can easily fit it to your case
var initial = 0;
var final = 5;
function change(current, expected){
if(current != expected){
setTimeout(function(){
current += ((expected-current > 0) ? 1 : -1)); //increment or decrement based on the case
change(current, expected);
}, 1000);
}
}
change(0, 5);
Here you have:
var interval = setInterval(gMoneyU1, 1000);
var Money = 0, U1Amount = 1; //Start U1Amount in 1
function gMoneyU1()
{
var calc = 5 * U1Amount;
Money += calc;
U1Amount++; //Increment amount by 1
document.getElementById('money').innerHTML=Money + "$";
}
Cheers
Here is my understanding of this question :
var money = 5,
ceiling = 10,
el = document.getElementById('money'),
tid = setInterval(update, 500);
function update() {
refresh(++money);
if (money === ceiling) clearInterval(tid);
}
function refresh(value) {
el.innerHTML = value + '$';
}
refresh(money);
Have a look at the demo : http://jsfiddle.net/wared/4DmxG/.

Categories

Resources