Take the 2-minute tour ×

I have a button that changes the background of a div when its rolled over. the background needs to change on a timer so i have used setTimout to execute methods that change the backgrounds. I thought clearTimeout would cancel and timeouts i have set so i put this on the mouseleave event. However it doesnt seem to stop the timeouts. Is my logic right here?

$("#h2Buzz").mouseenter(function () {   
   setTimeout(playV(), 2700);
   setTimeout(playP(), 5400);
$("#h2Buzz").mouseleave(function () {

function playV() {
    $("#ServicesBackgroundImage2").css("background-image", "url(/images/v.jpg)");
function playPn() {

    $("#ServicesBackgroundImage2").css("background-image", "url(/images/p.jpg)");
share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

Assign a variable to your setTimeout, which you then pass to clearTimeout to clear it, i.e.

var play_timeout = setTimeout("playV()", 2700);

(Note I added quotes around your first setTimeout argument)

share|improve this answer
No need to use quotes, just pass the function name: var play_timeout = setTimeout(playV, 2700); –  some Apr 9 '12 at 4:06
add comment

You are using setTimeout and clearTimeout wrongly. The setTimeout function returns a handle to the timeout, which is to be passed into clearTimeout to stop it.

var playVTimeout;


    playVTimeout = setTimeout(playV, 2700);



Also note that setTimeout(playV(), 2700); will call playV() now and execute its return value 2.7 seconds later. You should pass a function object playV in instead.

share|improve this answer
add comment

When you call setTimeout, it returns a numeric value. You should store this value, because this is what you need for clearTimeout. So keep track of the return value from both setTimeout's (they will be different). And keep track of them in a scope you can access from both functions.

Quick 'n' Dirty Example:

var timer = setTimeout( function(){ alert('hi'); }, 300 );
clearTimeout( timer );

Also, you are calling setTimeout with 'playV()', this is incorrect as it will immediately call that function this way. You can leave the brackets behind, so just setTimeout( playV, 3500 );

share|improve this answer
add comment

Your Answer


