1
let k = 0;
function change() {
    let doc = document.body;
    let color = ["black", "blue", "brown", "green"];
    doc.style.backgroundColor = color[k];
    k++;
    if (k == color.length) {
        k = 0;
    }
}
setInterval(change, 1000);

**And I write **

function change2() {
 let doc = document.body;
 let color = ["black", "blue", "brown", "green"];
 for (let r=0; r<color.length; r++){
     doc.style.backgroundColor = color[r];
 }
}
setInterval(change2, 1000);

First function work, but second function does not work. I do not understand this logic. Please explain me, basic logic. Please note--I am new JavaScript!

1
  • As in the change2 function you are not incrementing k, and always setting the background color as the 0th color in the colors array i.e. black. Commented Jan 3, 2021 at 18:04

3 Answers 3

1

It's because of the scope of r and k. In your first example you are declaring k outside of function change, and re-assigning every-time your change function is called and resetting it on a specific condition. While in second example r is declared and re-assigned all in same function call.

So, apparently in second example body colour is changing from black to green very very quickly and it is happening every second.

Sign up to request clarification or add additional context in comments.

Comments

0

You want to switch background colors one at a time, but the change2 function never increments k, so it will only change the background to the first color. Moreover, the loop is unnecessary since you only want to change colors once every second.

Even if you change it to use k as the loop variable, you are switching between all the colors when you should just be switching to the next one.

8 Comments

@Developer You don't need a loop. Why are you trying to write it like that?
@Developer Your first method works fine, so what are you trying to achieve with this?
I made a mistake when I wrote the code here. I have changed now. But still the result did not change
I don't understand the difference between these functions. Why result different?
@Developer Because one function has a loop and the other does not.
|
0

change k with r

function change2() {
    let doc = document.body;
    let color = ["black", "blue", "brown", "green"];
    for (let r=0; r<color.length; r++){
        doc.style.backgroundColor = color[r];
    }
}
setInterval(change2, 1000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.