0

I have a function foo() and want to call it in three times as below

function foo() {
  // function code goes here
}

foo();

$(window).resize(function() {
  setTimeout(function(){foo();}, 300);
});

$('#div').scroll(function() {
  setTimeout(function(){foo();}, 300);
});

I want to know if there is any short way to call it in all three situations.

4

2 回答 2

1
function foo(delay) {
    setTimeout(function() {

        // function code goes here

    }, delay||300);
};

$(window).on('resize', foo);
$('#div').on('scroll', foo);

foo(0);
于 2013-11-09T18:47:47.630 回答
1

If your using setTimeout with foo a lot, why not move it inside the function with an extra arg?

function foo(time) {
    time = time ? time : 0;    //default of 0
     setTimeout(function(){
          // function code goes here
    }, time);
}

foo();

$(window).resize(function() {
  foo(300);
});

$('#div').scroll(function() {
  foo(400);
});
于 2013-11-09T18:52:45.430 回答