I’m trying to create a 6 second delay before the heartColor(e) function begins, the function will then continue to loop. I don’t understand why it’s starting the function immediatley, and not waiting the 6 seconds it’s supposed to, what did I do wrong?
function heartColor(e) {
e.animate({
color: '#7ea0dd'
}, 1000).animate({
color: '#986db9'
}, 1000).animate({
color: '#9fc54e'
}, 1000, function(){
heartColor(e)
})
}
$('.something').hover(function(){
setTimeout(heartColor($(this)), 6000);
})
The
setTimeout()function expects its first parameter to be a function reference (or a string, but that’s not recommended for several reasons). You are not passing it a function reference, you are calling theheartColor()function and passing the result tosetTimeout(). So the function executes immediately, and then after six seconds nothing happens because the return value was undefined sosetTimeout()had nothing to work with.Try this instead:
The reason I have included an anonymous function as the parameter to
setTimeoutis that your call toheartColor()needs to pass a parameter through. If it didn’t have any parameters you could do this:Note there are no parentheses after
heartColor– that gets a reference to the function without calling it so that latersetTimeoutcalls it for you. But you can’t get a reference to the function and provide parameters at the same time so you need to wrap the call up in another function. You could do this:My original answer with the anonymous function is kind of short hand for that and (most people find it) more convenient.
The reason I have created a variable
$thisis because of the way thethiskeyword works in JavaScript, which depends on how a function is called. If you simply saidheartColor($(this))inside the anonymous function (or thecallHeartColor()function)thiswould not be the element being hovered over.