0

I got 7 variables (seconds), I am using them to show countdown. All of them counting down simultaneously at the same page. I want to set them to '59' after they reached to '0'. I am new to javascript so sorry if it is a silly question.

Here is my code :

s--; s2--; s3--; s4--; s5--; s6--; s7--; 

        var array_s = [s, s2, s3, s4, s5, s6, s7]; 
        for (var i = 0; i < array_s.length; i++) {
            var result = array_s[i];
            if( result < 0) {
                result = 59;
            }
        }

Edit: tried this way, too:

var array_s = [s, s2, s3, s4, s5, s6, s7]; 
for (var i = 0; i < array_s.length; i++) {
    if( array_s[i] < 0) {
        array_s[i] = 59;
    }
}

But they keep counting down after '0'. So, Where is my problem, what am I doing wrong?

Edit: I have edited the mistake in length

ctarimli
  • 322
  • 4
  • 25

5 Answers5

2

You made a typo, lenght should be length.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Alberto
  • 4,212
  • 5
  • 22
  • 36
1

primitive types such as 'result' is not a reference to the index in the array, its just the value. You need to update the array.

if (result < 0)
  array_s[i] = 59
clueless_user
  • 131
  • 1
  • 1
  • 8
0

Just don't load it into the result var, and use length:

var array_s = [s, s2, s3, s4, s5, s6, s7]; 
for (var i = 0; i < array_s.length; i++) {
    if( array_s[i] < 0) {
        array_s[i] = 59;
    }
}
Nicky Smits
  • 2,980
  • 4
  • 20
  • 27
0

You're setting result back to 59, but you're never setting that value back to the appropriate sN variable. Setting array_s[i] alone wouldn't work with your code as it is now, because that will just correct the values within the array, not the sN variables.

I'd recommend getting rid of the sN variables entirely and just using an array:

// initialize array once
var array_s = [...]; 

...

for (var i = 0; i < array_s.length; i++) {
    var result = array_s[i];
    result--;                // decrement each value
    if(result < 0) {         // check for values < 0
        result = 59;
    }
    array_s[i] = result;     // update values
}

Demonstration

Note: In this demonstration, I've significantly accelerated the timer so you can easily see the values decrementing down past 0 and resetting. Also, it's important to realize that setInterval and setTimeout are not particularly accurate, so if you really need to make your timers accurate down to the second, you'll probably need to use another method—e.g. using Date objects.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 1
    @ctarimli The key thing is to get rid of the `sN` variables. See my updated answer for a demonstration of how this might work. – p.s.w.g Mar 08 '14 at 01:57
0

Yes, you need to update the variables from the array:
[s, s2, s3, s4, s5, s6, s7] = array_s;
see Andy E's answer:
Unpacking array into separate variables in JavaScript

Community
  • 1
  • 1
dcromley
  • 1,373
  • 1
  • 8
  • 23