If you want an equal interval, your loop is fine, you just need to fix the math for calculating the timeout:
const btn = document.getElementById('btn');
btn.addEventListener('click', function(){
for (let index = 10; index > 0; index--) {
setTimeout(() => {
console.log(index)
}, 1000*(10-index));
}
})
<div class="app">
<button id="btn">click</button>
</div>
That will count down from 10 to 1 once every second, just change the 1000 as needed if you want it to be faster or slower.
Note that the order of the loop doesn't actually matter here (aside from a few ms difference in execution time) since it's asynchronous - you could use a non-reversed loop and still get the same result to the human eye.
Answer from John Montgomery on Stack OverflowReverse for loop in JavaScript - Stack Overflow
javascript - How to reverse the order in a FOR loop - Stack Overflow
For loop backwards
javascript - Are loops really faster in reverse? - Stack Overflow
Videos
If you want an equal interval, your loop is fine, you just need to fix the math for calculating the timeout:
const btn = document.getElementById('btn');
btn.addEventListener('click', function(){
for (let index = 10; index > 0; index--) {
setTimeout(() => {
console.log(index)
}, 1000*(10-index));
}
})
<div class="app">
<button id="btn">click</button>
</div>
That will count down from 10 to 1 once every second, just change the 1000 as needed if you want it to be faster or slower.
Note that the order of the loop doesn't actually matter here (aside from a few ms difference in execution time) since it's asynchronous - you could use a non-reversed loop and still get the same result to the human eye.
If you use promises and async/await you can avoid the setTimeout overload and have precise control. The difference between this and John Montgomery's answer is this doesn't care how many times you loop. Do 10000 if you want, you won't get 10000 setTimeouts running at the same time.
const btn = document.getElementById('btn');
const wait = time=>new Promise(resolve=>setTimeout(resolve,time))
btn.addEventListener('click', async function(){
for (let index = 10; index > 0; index--) {
await wait(1000)
console.log(index)
}
})
<div class="app">
<button id="btn">click</button>
</div>
Async functions allow you to use the await keyword. This is a neat new feature in javascript that let's you write async code (like setTimout) as if it was sync.
const wait = time=>new Promise(resolve=>setTimeout(resolve,time))
is a fairly common helper function developers keep around for times you need to just wait some amount of time and then do something. By await'ing the wait(1000) function, I hang the execution of the loop until the time is done.
var num = 10,
reverse = false;
if(!reverse) for( var i=0;i<num;i++) log(i);
else while(num-- ) log(num);
// to avoid duplication if the code gets long
function log( num ) { console.log( num ); }
EDIT:
As noted in the comments below, if i is not declared elsewhere and you do not intend for it to be global, then declare it with the other variables you declared.
And if you don't want to modify the value of num, then assign it to i first.
var num = 10,
reverse = false,
i;
if(!reverse) for(var i=0;i<num;i++) log(i); // Count up
else {var i=num; while(i--) log(i);} // Count down
function log( num ) { console.log( num ); }
Try use 2 loops:
if (reverse) {
for(i=num-1;i>=0;i--){
console.log(i)
}
}
else {
for(i=0;i<num;i++){
console.log(i)
}
}
It's not that i-- is faster than i++. Actually, they're both equally fast.
What takes time in ascending loops is evaluating, for each i, the size of your array. In this loop:
for(var i = array.length; i--;)
You evaluate .length only once, when you declare i, whereas for this loop
for(var i = 1; i <= array.length; i++)
you evaluate .length each time you increment i, when you check if i <= array.length.
In most cases you shouldn't even worry about this kind of optimization.
This guy compared a lot of loops in javascript, in a lot of browsers. He also has a test suite so you can run them yourself.
In all cases (unless I missed one in my read) the fastest loop was:
var i = arr.length; //or 10
while(i--)
{
//...
}
You can use it like this
for (var i = 10; i >= 0; i--)
But I'm not sure why are you doing so because you are not using this variable inside your loop so I think it doesn't make any difference to the output as you loop going to run 10 times either way.
If I could guess then I think you want to print the stars in reverse order of quantity. That means you want to have maximum stars in first row then -1 in second and so on.. If so then you need to reverse the order of inner loop only like this
function seethestars1() {
var stars = document.getElementById("emptytext2");
for (var i = 0; i <= 10; i++) {
for (var j = 10; j > i; j--) {
stars.value += "*";
}
stars.value += "\n";
}
}
Js Fiddle Demo
Just try the following code for seethestarts1 method.
function seethestars1() {
for (var i = 0; i <= 10; i++) {
for (var j = i; j > 0; j--) {
document.getElementById("emptytext2").value += "*";
}
document.getElementById("emptytext2").value += "\n";
}
}
pop (MDN, spec) is a mutator method: It changes the state of the array you call it on. So naturally, inArr.pop(1) modifies arr (in your first example), since inArr and arr both refer to the same array.
Probably worth noting as well that pop doesn't accept any parameters, so that 1 doesn't do anything.
In your first example, your best bet is to just assign another variable (say, j) the initial value arr.length - 1 and use arr[j] to get the value, then decrease j as you increase i. (Also, no point to inArr, and you need to declare i to avoid what I call The Horror of Implicit Globals:
function reverseArray (arr) {
var newArr = [];
for (var i = 0, j = arr.length - 1; i < arr.length; i++, j--) {
newArr[i] = arr[j];
}
return newArr;
}
console.log(reverseArray(["A", "B", "C", "D", "E", "F"]));
You can also just use arr[arr.length - i - 1] rather than a second variable:
function reverseArray (arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr[i] = arr[arr.length - i - 1];
}
return newArr;
}
console.log(reverseArray(["A", "B", "C", "D", "E", "F"]));
You could take a copy of the array and use the length of the copy for checking the next pop/push command.
function reverseArray(array) {
var newArr = [],
inArr = array.slice(); // take copy of primitive values
while (inArr.length) { // check decrementing length
newArr.push(inArr.pop());
}
return newArr;
}
console.log(reverseArray(["A", "B", "C", "D", "E", "F"]));
To fullfill the condition, you could use a for statement as well.
function reverseArray(array) {
var newArr = [],
inArr = array.slice(); // take copy of primitive values
for(; inArr.length; ) { // check decrementing length
newArr.push(inArr.pop());
}
return newArr;
}
console.log(reverseArray(["A", "B", "C", "D", "E", "F"]));
Array.prototype.reverse():
The
reverse()method reverses an array in place. The first array element becomes the last and the last becomes the first.
So you can reverse your array and use:
_.each(myItems.reverse(), print)
Or
_.each(myItems.slice().reverse(), print)
You can reverse a array in underscore.js as
.reverse()
so you can use
_.each(myItems.reverse(), print)
js Bin Example