简体   繁体   中英

Javascript: Passing arguments to an inner setTimeOut function?

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);
  });

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);
});

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 var s, so only the parameters are accessible within that function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM