Search code examples
javascriptjqueryjquery-animatesettimeoutjquery-hover

JavaScript issue: setTimeout


I'm trying to make a moving panel using JavaScript and jQuery.

I made this Working Demo, the JS part look like this:

$("nav.nav").hover(function(){
    $("nav.nav").animate({left:'-5px'},100,"swing");
  },
  function(){
    $("nav.nav").animate({left:'-170px'},100,"swing");
  });

As you can see, it's working, but I want to add a delay when I leave the panel because, some time, I leave the panel for 1 pixel by mistake and it's annoying.

I tried to use setTimeout("javascript function", milliseconds); like so:

$("nav.nav").hover(function(){
    $("nav.nav").animate({left:'-5px'},100,"swing");
  }, setTimeout(function(){
      $("nav.nav").animate({left:'-170px'},100,"swing");
  },10));

(The callback function in the timeout) but it's not working, and I have no idea why.


Solution

  • I'd recommend using jQuery's .delay() (combined with .stop(true)) which handles the timer stuff for you automatically:

    $("nav.nav").hover(function () {
        $("nav.nav").stop(true).animate({left: '-5px'}, 100, "swing");
    },function () {
        $("nav.nav").stop(true).delay(1000).animate({left: '-170px'}, 100, "swing");
    });
    

    Working demo: http://jsfiddle.net/jfriend00/LuNHR/