Why the following code prints "0 5 10 15 20 ... 100"?
(function () {
for ( var i = 100; i >= 0; i -= 5) {
(function() {
var pos = i;
setTimeout(function() {
console.log(" pos = " + pos);
}, (pos + 1)*10);
})();
}
})();
I declare pos = i , which should be in a descending order. This code originated from John Resig' fadeIn() function in his book Pro javascript techniques.
You're registering the timeouts in the correct order, the problem is they're timed in order of their value, so value 10 will be printed in 100ms, value 100 in 1000ms, etc.
So you need to change the timing calculation to subtract from the max value (in this case, 100)
(function () {
for ( var i = 100; i >= 0; i -= 5) {
(function() {
var pos = i;
setTimeout(function() {
console.log(" pos = " + pos);
}, (100 - pos + 1)*10); // note the subtraction here
})();
}
})();
Related
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.
I would like my program to return 10 random numbers but it isn't working it doesn't load the random numbers, I have linked the program to index.html so that's not the problem here, this is what I have tried:
function randomNumber(upper) {
return Math.floor(Math.random() * upper) + 1;
}
var counter = 0;
while (counter < 10) {
var randNum = randomNumber(6);
document.write(randNum + ' ');
counter += 1;
}
If it works in fiddle but not elsewhere it's most probably a problem with onload here as Doorknob already suggested.
function randomNumber(upper) {
return Math.floor( Math.random() * upper ) + 1;
}
window.onload = function () {
var counter = 0;
while (counter < 10) {
var randNum = randomNumber(6);
document.write(randNum + ' ');
counter += 1;
}
};
The bracketing with window.onload causes the code to wait until the whole page is loaded.
I am building a virtual joystick and this is part of the code that I made so that when the joystick is in between a certain value the x and y value will keep on incrementing by a certain value for instance when the joystick is between 1 and 20 for deltaX it will keep incrementing every second once or if it is in between 21 and 40 it will increment twice every second and I want it to keep incrementing and not staying at the same value of two. When I try this code, the x & y values just stick to 1, 2 or 3 and doesn't increment, could anyone suggest why this happens?
edit:
The If statements need to be outside the function as the joystick breaks and doesn't run if its inside.
if (joystick.deltaX() >= 1 && joystick.deltaX() <= 20) {
(function movex1() {
x = x + 1;
setTimeout(movex1, 1000);
})();
}
if (joystick.deltaX() >= 21 && joystick.deltaX() <= 40) {
(function movex2() {
x = x + 2;
setTimeout(movex2, 1000);
})();
}
if (joystick.deltaX() >= 41 && joystick.deltaX() <= 60) {
(function movex3() {
x = x + 3;
setTimeout(movex3, 1000);
})();
}
if (joystick.deltaY() >= 1 && joystick.deltaY() <= 20) {
(function movey1() {
y = y + 1;
setTimeout(movey1, 1000);
})();
}
if (joystick.deltaY() >= 21 && joystick.deltaY() <= 40) {
(function movey2() {
y = y + 2;
setTimeout(movey2, 1000);
})();
}
if (joystick.deltaY() >= 41 && joystick.deltaY() <= 60) {
(function movey3() {
y = y + 3;
setTimeout(movey3, 1000);
})();
}
When your code executes, joystick.deltaX() and joystick.deltaY() more likely have a value of 0, so no timeout is ever set.
Also, avoid so many ifs when you can just replace them with a division.
Why not use an interval?
var x = 0, y = 0;
// Execute every second
var intervalId = setInterval(function() {
x += Math.ceil(joystick.deltaX() / 20);
y += Math.ceil(joystick.deltaY() / 20);
}, 1000);
// Stop after 20 seconds
setTimeout(function() {
clearInterval(intervalId);
}, 20000)
I create a countdown function but it works just at the begining and then stops.
var rek_inter = setInterval(cnt(s_, d), 1000);
function cnt(deg, deg2) {
deg--;
while (deg < 0) {
deg = 59;
deg2--;
}
if (deg2 < 0) {
$('#s_').html("ok");
} else if (deg2 >= 0) {
var d_sn = fixd(deg2);
var s_sn = fixd(deg);
$('#s_').html(d_sn + ":" + s_sn);
}
}
function fixd(g) {
if (g < 10) {
return '0' + g;
}
return g;
}
I tried that, too;
var rek_inter = setInterval(function() {cnt(s_, d);}, 1000);
But result was same.
If I put the function into the interval function like that:
var rek_inter = setInterval(function () {
s_--;
while (s_ < 0) {
s_ = 59;
d--;
}
if (d < 0) {
$('#s_').html("ok");
} else if (d >= 0) {
var d_sn = fixd(d);
var s_sn = fixd(s_);
$('#s_').html(d_sn + ":" + s_sn);
}
}, 1000);
function fixd(g) {
if (g < 10) {
return '0' + g;
}
return g;
}
It works. But I need that as I wrote first at the top. What could be the problem and solution here?
"I have lot of s_, s_2, s_3.... and d, d1, d2... values and I want to use them in single setInterval, this is why I am tryng to use cnt(s_, d); if that will work I will write cnt(s_2, d2), cnt(s_3, d3).."
You could just use closures to your advantage here.
var rek_inter1 = setInterval(cnt(s_2, d2), 1000),
rek_inter2 = setInterval(cnt(s_3, d3), 1000);
function cnt(deg, deg2) {
return function () {
deg--;
while (deg < 0) {
deg = 59;
deg2--;
}
if (deg2 < 0) {
$('#s_').html("ok");
} else if (deg2 >= 0) {
var d_sn = fixd(deg2);
var s_sn = fixd(deg);
$('#s_').html(d_sn + ":" + s_sn);
}
};
}
The first attempt is the same as :
setInterval ( value, time) ;
Here value = cnt(s_, d), the result of the call of the cnt function.
This cannot work, since setInterval expects a function. Too bad it silently fails in javascript.
In the second attempt, the issue is that you modify only function var, so no change can occur : you change deg, deg2, when in fact you would like to change s_ and d.
The third attempt is right, since you both invoke a function and change the globals s_ and d.
I would rather write it this way :
var rek_inter = setInterval( iterate , 1000);
function iterate () {
s_--;
while (s_ < 0) {
s_ = 59;
d--;
}
if (d < 0) {
$('#s_').html("ok");
} else if (d >= 0) {
var d_sn = fixd(d);
var s_sn = fixd(s_);
$('#s_').html(d_sn + ":" + s_sn);
}
}
Edit :
The O.P. mentionned that he wants to handle a set of (s_, d ) parameters.
I suggest you create an array of object which contains such parameters :
var sdParameters = [];
sdParameters.push( { s : some value , d: some other value} );
sdParameters.push( { s : some value 2, d: some other value 2 } );
... // (or using a for loop to grab the ds and ss if possible)
Then after each s/d object is defined by its index, so with :
function iterate (ind) {
var s_ = --sdParameters[ind].s ;
while (s_ < 0) {
s_ = 59;
sdParameters[ind].d--;
}
var d = sdParameters[ind].d;
if (d < 0) {
$('#s_').html("ok");
} else if (d >= 0) {
var d_sn = fixd(d);
var s_sn = fixd(s_);
$('#s_').html(d_sn + ":" + s_sn);
}
}
you can have all your intervals running on one single global array with :
var rek_inter = setInterval( iterate.bind(null,0) , 1000);
var rek_inter1 = setInterval( iterate.bind(null,1) , 1000);
(obviously you can/should store the intervals in an array, you might store them within sdParameters.
One last remark : i couldn't use relevant variable names, since i couldn't guess the use. Using significant names in your code can be of great help when things gets more complex.
The problem I faced is I can't figure out how to make the animated bar synchronously to the
percentage I. Right now I looks OKE but when I change the value '43' to '100' the percentage counter goes to slow.
example code:
$(document).ready(function(){
$(".barInner").animate({
width: 43 + "%",
opacity: 1
}, 2500 );
var display = $('.barInner');
var currentValue = 0;
var nextValue = 43;
var diff = nextValue - currentValue;
var step = ( 0 < diff ? 1 : -1 );
for (var i = 0; i < Math.abs(diff); ++i) {
setTimeout(function() {
currentValue += step
display.text(currentValue + "%");
}, 54 * i)
}
});
http://jsfiddle.net/vTKw7/
Thanks in advance,
Nick
You can't synchronize an .animate() and a setTimeout() the way you seem to want. Try using your setTimeout to control the width of the progress bar and display the percentage number at the same time.
$(document).ready(function () {
var display = $('.barInner');
var currentValue = 0;
var nextValue = 100;
var diff = nextValue - currentValue;
var step = (0 < diff ? 1 : -1);
for (var i = 0; i < Math.abs(diff); ++i) {
setTimeout(function () {
currentValue += step;
display.text(currentValue + "%");
$(".barInner").css({
width: currentValue + "%",
opacity: 1
});
}, 54 * i)
}
});
http://jsfiddle.net/mblase75/6TMWm/
Or, using .stop().animate() to smooth it out a little:
$(".barInner").stop().animate({
width: currentValue + "%",
opacity: 1
},50);
http://jsfiddle.net/mblase75/6TMWm/1/