1

私はこの機能を持っています

 function () {
     if ($(window).scrollTop() >= ($(document).height() - $(window).height()) * 0.7) {
         //$(window).unbind('scroll');

         jQuery.get('moreProfileComments', function (e, success) {
             $(window).scroll(scrollEvent);
             console.log(e);
             var result_div = $(e).find('#user_comments #u_cont div');
             var original_div = $('#user_comments #u_cont div');

             if (result_div.last().html() === original_div.last().html()) {
                 //alert("TEST");
                 //$(window).unbind('scroll');
             } else {
                 //$(rs).appendTo('#search_results').fadeIn('slow');
                 $('#user_comments #u_cont').append($(e).find('#user_comments #u_cont').html());
                 $(window).scroll(scrollEvent);
             }
         }, "html");

     }
 };

それはajaxリクエストを作成しますが、1つのajaxリクエストのみを起動するようにするにはどうすればよいですか?リクエストがすでに送信されているか送信されている場合。複数のajaxリクエストは必要ありません。

4

2 に答える 2

3

scrollイベントのようなresizeイベントは100回発生します(ブラウザによって異なります) 。underscore.jsthrottleなどのメソッドを提供するプラグインを使用するか、関数を使用できます。setTimeout

underscore.jsのthrottle例:

var throttled = _.throttle(scrollEvent, 500);
$(window).scroll(throttled);

setTimeout関数を使用した例:

var timeout = '';
$(window).on('scroll', function(){
    clearTimeout(timeout);
    timeout = setTimeout(function(){
       // Do something here
    }, 300); 
})

John Resigによる関連記事:http: //ejohn.org/blog/learning-from-twitter/

于 2013-03-17T07:42:19.023 に答える
2

resizeおよびイベントには、スロットルバージョンのイベントハンドラーを使用することをお勧めしscrollます。ただし、複数のリクエストを行う際の特定の問題に対処するには、次のコードを使用できます。

 var requestIsRunning; //Flag to indicate that there is a pending request.

 function () {
     if ($(window).scrollTop() >= ($(document).height() - $(window).height()) * 0.7) {

         //do nothing if there is an active moreProfileComments request;
         if(ruquestIsRunning) {return;};

         requestIsRunning = 1;
         jQuery.get('moreProfileComments', function (e, success) {
             $(window).scroll(scrollEvent);
             console.log(e);
             var result_div = $(e).find('#user_comments #u_cont div');
             var original_div = $('#user_comments #u_cont div');

             if (result_div.last().html() === original_div.last().html()) {
                 //alert("TEST");
                 //$(window).unbind('scroll');
             } else {
                 //$(rs).appendTo('#search_results').fadeIn('slow');
                 $('#user_comments #u_cont').append($(e).find('#user_comments #u_cont').html());
                 $(window).scroll(scrollEvent);
             }
         }, "html")
         //when request is complete restore the flag
         .always(function(){ 
              requestIsRunning = 0;
          });

     }
 };
于 2013-03-20T10:49:13.707 に答える