0

I have a thumbnail scroller where I want to trigger some action only when the mouse is hovered for 3 seconds on thumbnails. I have the following code but the inner setTimeOut function is not getting the arguments from the outer function--the sourceURL console output gets 'undefined' error. But the 'hover' function I do see correct sourceURL value. Thanks in advance!

   var tOut;
   $('img.thumb').hover(function(){
      var sourceURL = $(this).attr('src');
      var lat = $(this).attr('lat');
      var lng = $(this).attr('lng');
      tOut = setTimeout(function(sourceURL,lat,lng){
      console.log(sourceURL);//undefined
      map.setView(new L.LatLng(lat, lng), (init_mapzoom+2));
    },3000);
   },function(){
     clearTimeout(tOut);
  });
2
  • Thanks. But what code? Commented Nov 14, 2014 at 15:19
  • No. The setTimeOut needs to get the arguments from the hover function. Commented Nov 14, 2014 at 15:20

2 Answers 2

1

You don't need to pass the variables to the function. As the function is created in a scope where the variables exist, they are caught in the closure for the function so the function can use them even after the scope is gone:

var tOut;
$('img.thumb').hover(function(){
  var sourceURL = $(this).attr('src');
  var lat = $(this).attr('lat');
  var lng = $(this).attr('lng');
  tOut = setTimeout(function(){
    console.log(sourceURL);
    map.setView(new L.LatLng(lat, lng), (init_mapzoom+2));
  },3000);
},function(){
  clearTimeout(tOut);
});
Sign up to request clarification or add additional context in comments.

Comments

1

The function given to setTimeout doesn't have to receive them as arguments.

By also being defined within the .hover() function, it will have sourceURL, etc. in scope.

$('img.thumb').hover(function(){
  var sourceURL = $(this).attr('src');
  // ..

  tOut = setTimeout(function(){
    console.log(sourceURL);
    // ...
  }, 3000);
}, ...);

Using them again as named parameters will shadow the vars, so only the parameters are accessible within that function.

1 Comment

Thanks! Would accept your Answer but Guffa's came first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.