I pass the value of the referred paragraph to a new function and it gets loaded in the new function with the “this” keyword.
Works okay.
But then I want to use setTimeout to delay the function.
How can I pass the value of the this keyword through that setTimeout ?
With this code it doesn’t work out:
function firstChange(){
setTimeout("changeNew",2000);
}
function secondChange(){
setTimeout("changeOld()",3000);
}
// the doMyFunc events are linked to these functions above right now
function doMyFunc(){
var thePars = document.getElementsByTagName('p');
for (var i=0; i<thePars.length; i++){
thePars[i].onmouseover = firstChange;
thePars[i].onmouseout = secondChange;
}
}
Does someone have a good tutorial around this issue?
Pardon, I misunderstood that the timeout event wasn’t working as expected.
One possible way to achieve it is to have each timeout function call the other timeout function.
When the mouseout event occurs you can then clear the timeout event and set the style to finish things off.
Yes, that’s a common problem that comes about from not quite understanding what’s occurring.
When the timeouts have been set up and the loops are completed, the timeouts run the appropriate functions which use the variables as they are at the time when those functions are run, not when they were set up.
If you want the variable from the loop to be retained, you will need to pass it to the function as well.
This means not just passing the this keyword to the function as context, but also passing interval to the function as interval.
And if, for example, you want to let these 2 styles change a few times after each other, for creating a blinking effect. How do you put this in a loop?
It’s not repeating the loop with this one:
function changeStyles(){
var interval = 500;
for (var t = 0; t<5; t++){
setTimeout(function (context) {
return function () {
firstStyle.call(context);
};
}(this), interval);
setTimeout(function (context) {
return function () {
secondStyle.call(context);
};
}(this), interval*2);
}
}