如何防止一次多次的函数调用

时间:2017-07-05 09:05:07

标签: javascript jquery node.js

我有一种情况,我想只调用function一个time,但多次firing如何防止这种情况。

http://jsfiddle.net/pdzTW/224/

function howManyTimesIwasCalled(value){
  console.log('i have called so many time '+value);
}

$(document).ready(function() {
  alert('please scroll output window and check the console');

  $(document).scroll(function() {
    var cutoff = $(window).scrollTop() + 200;

    $('div').each(function(e) {
      if ($(this).offset().top + $(this).height() > cutoff) {
        $('div').removeClass('current');
        $(this).addClass('current');
        howManyTimesIwasCalled($(this).data('value'));

        //callGoogleMapHere(data..);

        return false; // stops the iteration after the first one on 
      }
  });
});

2 个答案:

答案 0 :(得分:1)

在这里:http://jsfiddle.net/tvv1tqmb/

function howManyTimesIwasCalled( value ) {
    console.log( 'i have called so many time ' + value );
}

$( document ).ready( function () {
    alert( 'please scroll output window and check the console' );
    var lastDiv = undefined;
    $( document ).scroll( function () {
        var cutoff = $( window ).scrollTop() + 200;

        $( 'div' ).each( function ( e ) {
            if ( $( this ).offset().top + $( this ).height() > cutoff ) {

                if ( $( this ).data( 'value' ) == lastDiv ) {
                    return false;
                }

                $( 'div' ).removeClass( 'current' );
                $( this ).addClass( 'current' );


                howManyTimesIwasCalled( $( this ).data( 'value' ) );

                //callGoogleMapHere(data..);

                lastDiv = $( this ).data( 'value' );

                return false; // stops the iteration after the first one on 
            }
        } );
    } );
} );

答案 1 :(得分:0)

滚动事件和调整大小事件会在用户执行此操作时多次触发。为了防止这种情况。使用全局布尔值来检查函数是否已被触发。

var tmp = 0;
$.fn.scrollStopped = function(callback) {           
  $(this).scroll(function(){
    if(tmp == 0){
      var self = this, $this = $(self);
      if ($this.data('scrollTimeout')) {
        clearTimeout($this.data('scrollTimeout'));
      }
      $this.data('scrollTimeout', setTimeout(callback,300,self));
      tmp = 1;
    }
  });
};


$(window).scrollStopped(function(){
    console.log('Test')
  tmp=0;
})