I have a var which I tried to make the value of it count up till 100. When it reaches 100 it should count back to 0. this is my experimentation code.
var min = 0 - 1,
max = 100 + 1,
now = 0;
var timer = setInterval(function(){
if(now <= max){
now++;
console.log(now);
}else if ( now >= min){
now--;
console.log(now);
}
},500);
The code works till it counts up to 100, but it doesn't count it back to 0, and repeat the same process over and over again.
Can anyone give me a clue what I am doing wrong, or if I'm doing it completely wrong. Can you please explain the method I should use?
Use a variable step = +1; which will change to step = -1; as soon as you reach the maximum:
var min = 0,
max = 100,
step = +1,
now = 0;
var timer = setInterval(function(){
if(now >= max) {step = -1;}
if(now <= min) {step = +1;}
now += step;
console.log(now);
}, 20);
try this please:
var count = 'up';
var min = 0 - 1,
max = 100 + 1,
now = 0;
var timer = setInterval(function(){
if(count === 'up'){
if(now <= max){
now++;
}
else{
count = 'down';
now--;
}
}
else{
if(now >= min){
now--;
}
else{
count = 'up';
now++;
}
}
console.log('now: ' + now);
},500);
Try this demo (count until 10 to reduce time of execution)
DEMO
just think about what you are doing. When the count is up on 101, it does not count up because the if statement is false. so you decrease back to 100. But in the next loop, the first if statement is true again and you increase.
You could set a flag the first time you decrease, and add the flag into the first if condition, meaning, once the flag is set you never increase the value again.
Related
I want to call the boss[i].showBoss() and .moveBoss() functions every time the counter is 10,20,30,40...(dividable by 10), ( if(counter % 10 === 0) works only when the counter is at a number divisible by 10, not the others), but this hard-coded example only runs the code once after counter == 10, not when counter == 20,30,40 etc. Any suggestions on how I can can start the functions every time counter % 10 == 0, but not stop them after the counter is not % 10, for instance 11?
function draw() {
// put drawing code here
background(220);
if (counter >= 10) {
for(i = 0; i < boss.length; i++){
boss[i].showBoss();
boss[i].moveBoss();
}
} else if (counter >= 20) {
for(i = 0; i < boss.length; i++){
boss[i].showBoss();
boss[i].moveBoss();
}
} else if (counter >= 30) {
for(i = 0; i < boss.length; i++){
boss[i].showBoss();
boss[i].moveBoss();
}
}
}
Create an object to represent your boss action you want to start. When divisible by 10, create one of these and added to a list of bosses to draw. Every draw loop, draw all your bosses.
let bossesToDraw = [];
function draw(){
if(counter % 10 == 0){
bosses.push({
// state for the boss like its current position
// this could also create a new boss if you have a proper object
});
}
bosses.forEach(function(boss){
boss.showBoss();
boss.moveBoss()
});
//maybe check if you should remove the boss
}
You are kind of answering your own question here...
Can't you just do:
function draw() {
// put drawing code here
background(220);
if (counter % 10 === 0) {
for (i = 0; i < boss.length; i++) {
boss[i].showBoss();
boss[i].moveBoss();
}
}
}
The function draw() will run anyways. What you need to do is to check when your counter is divisible by 10, your instruction counter % 10 === 0 works fine for that.. Here I've mimic the draw function behaviour with a setInterval. Please note that the draw function is now an arrow function, that's to have access to the counter variable in the scope. This is irrelevent in your case.
let counter = 0;
let draw = () => {
// we do normal draw things
// background(255);
if(counter % 10 === 0) {
// we need to animate the boss.
console.log('current counter was divisible by 10', counter);
}
counter ++;
};
setInterval(draw, 100)
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>
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)
I have the following function which I would like to simplify with a for loop maybe but don't know how to do it. any help will be much appreciated. Basically, if the field value is 0 or null then my total value (field) should be 0 otherwise if the field value is from 1 until 1000 then the total value becomes 5000. For every 1000 (i.e. 1001 until 2000) my total value should increase by 50 i.e. 5050. This should continue until the field value reaches 200000 and the total is 50000.
function calc56() {
var56 = parseFloat(document.getElementById('units56').value - 0);
if (var56 == '' || var56 == 0) {
document.getElementById('amount56').value = 0;
}
else if (var56 < 1000) {
document.getElementById('amount56').value = 5000;
}
else if ((var56 > 1000) && (var56 <= 2000)) {
document.getElementById('amount56').value = 5050;
}
else if ((var56 > 2000) && (var56 <= 3000)) {
document.getElementById('amount56').value = 5100;
}
}
Thanks in advance.
function calc56() {
var el = document.getElementById('units56'); //reference the dom element
var val = +el.value; //convert to float
if (!val) { //if no value, leave untouched
} else if (val < 0) { //if value is less than 0, make it 0.
el.value = 0;
} else { //otherwise, calculate new value
var mod = Math.floor(val / 1000); //calc how many 1000s fit in the value
el.value = mod * 50 + 5000; //use at least 5000, and add 50 for every 1000
}
}
I would suggest you also change the name of the function, as it's not very useful. However, this code right here should be the most efficient you can get while still keeping it readable.
If you need more clarification, feel free to ask in a comment!
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/.