We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi ! I was trying to change the color of the background every 0.1 seconds with setInterval, turning it to white. And I couldn't make it without hardcoding the variable inside the function.
let y, color1, color2;
function setup(){
createCanvas(400, 300);
y = 0;
color1 = 0;
changeColor(color1, 100);
}
function changeColor(thecolor, wait){
setInterval(startt, wait);
function startt(){
thecolor++;
// color1++;
}
}
function draw(){
background(color1);
stroke(255);
line(0, y, width, y);
y+=5;
if(y > height){
y = 0;
}
}
Answers
You're only ever changing
thecolor
which is passed into your function. This doesn't change the original value.You should also debug your code to make sure your function is actually firing like you expected.
But taking a step back, it feels a little weird to use
setInterval()
at all. Can't you just use theframeCount
variable or themillis()
function to do your own timing?changeColor(color1, 100);
0
.More about closures: https://Developer.Mozilla.org/en-US/docs/Web/JavaScript/Closures
Oooh... I get it. But, then, it works different when a dom element is passed as an argument for the parameter of the function isn't it ?
Because I do can change the content of a dom element, with ".html" in the function for example.
(example that I've been using to learn, in this video https://youtube.com/watch?v=-jysK0nlz7A&list=PLRqwX-V7Uu6ZmA-d3D0iFIvgrB5_7kB8H&index=6 )
It may seem it's different, but it's still pass-by-value. @-)
It's tricky to explain, but I'll try it out. :-\"
I pretty much bet when you had mutated that DOM element, you did it so via the dot operator
.
, right? :>That is, you haven't reassigned another object to the parameter itself, but mutated the object already stored in it using the dot
.
access operator. L-)https://Processing.org/reference/dot.html
To better explain it I did the pure JS example below. :bz
Since it's just JS, you can open your browser's console by hitting F12 and paste this code there: :-bd
Ooohhh !!! If I wanted to change the name of the animal to Feefee. I could writte
In that case I would be working with two objects created before. Ill check the reference