Jquery Function Call Not Working
Solution 1:
spanId
is being incremented before the timeout finishes, so you are trying to remove the class from the next item instead of the last item.
The usual way to avoid this problem is to use a closure, but in this case it would be much simpler to move spanId++;
to the end of the remove
function.
The closure approach (which I don't recommend in this case as it is overly complicated compared to just moving the increment) could look like this:
setInterval(changeClass, 4000);
var spanId = 1;
functionchangeClass() {
$('#' + spanId).addClass("hilite");
setTimeout(
remove(spanId), // CALL remove and pass spanId as an argument1000
);
spanId++;
}
functionremove(spanId) {
returnfunction () { // RETURN a function from remove().// Note: This spanId is the local variable defined in the argument list// not the one that exists in the wider scope
$('#' + spanId).removeClass("hilite");
returntrue;
}
}
Solution 2:
You should put it that way :
setInterval(changeClass, 4000);
var spanId = 1;
functionchangeClass() {
$('#'+spanId).addClass("hilite");
setTimeout(remove, 1000);
}
functionremove() {
$('#'+spanId).removeClass("hilite");
spanId++; // <--returntrue;
}
Edit : [due to Quentin suggesting to use diff tool, thank you Quentin]
I put the spanId++ at the end of remove function, so that the changeClass and remove functions are both called with the same value of spanId at each call.
Solution 3:
functionchangeClass(){
$('#'+spanId).addClass("hilite");
setTimeout(remove, 1000);
spanId++;}
In this code, you should execute spanId++
in a callback function which is passed as parameter to setTimeout since JS won't halt the execution until it finishes setTimeout statement.
So your code should look like this:
functionchangeClass(){
$('#'+spanId).addClass("hilite");
setTimeout(remove, 1000);
}
functionremove(){
$('#'+spanId).removeClass("hilite");
spanId++;
returntrue;
}
Solution 4:
This works for me, adds some timeout control too.
changeClass();
functionchangeClass(){
$("#container").addClass("box");
console.log("changeClass()");
clearTimeout(interval);
interval = setTimeout(remove, 1000);
}
functionremove(){
$("#container").removeClass("box");
console.log("remove()");
clearTimeout(interval);
interval = setInterval(changeClass,1000);
}
Post a Comment for "Jquery Function Call Not Working"