开发者

How to initiate a function including AJAX request some time after the user's last input?

This is the crucial code:

var ajaxCallTimeoutID = null;
$(document).ready(function() {
 $("input[id^='question']").live('keyup',function(ev){
    id=this.id.substr(8);
    if (ajaxCallTimeoutID != null)
    clearTimeout(ajaxCallTimeoutID);
ajaxCallTimeoutID = setTimeout(subjectivecheck(id), 1000);

}); 
});

However,

subjectivecheck(id) is immediately executed when a user inputs a letter, but I hope it is called after the user has stopped typing for a specified amount of time. How to solve this problem?

function subjectivecheck(id){
    var cost=(new Date().getTime() - start.getTime())/1000;
    var value=$('#question'+id).val();
    $.post("subjectivecheck.php?",{val:value, qid:id,time:cost, a_id:"<?php echo $announcementid; ?>"},function(xm){

        switch(parseInt(xm)){
            case 4:
            { $htm='Congrats,开发者_高级运维you have passed the test.';
                $('#success').css({"color":"green"});
                $('#success').text($htm);
            return; 
            }
            case 1:
            {
            $htm='V';
        $('#sign'+id).css({"color":"green"});
        $('#sign'+id).text($htm);
        break;  
            }
            case 0:{

                 $htm='X';
        $('#sign'+id).css({"color":"red"});
        $('#sign'+id).text($htm);
        break;
            }
            case 3:{
                $('#subjectivequestion').text('You have failed at this announcement.');

                $('#choicequestions').text(" ");
            }
        }

    });

}


You need to wrap it in an anonymous function:

ajaxCallTimeoutID = setTimeout(function(){subjectivecheck(id)}, 1000);

Without the wrapped function(){} the function subjectivecheck gets called immediately, but when you wrap it you pass a reference to the function as an argument. Later that function can be called, which will then call your function.


What I usually do is start the timeout on keyup, and clear the timeout on keydown (or keypress).

var timers=[];
$('input[id^="question"]').keydown(function(){
  while(timers.length){
    clearTimeout(timers.shift());
  }
}).keyup(function(){
  var timeout=setTimeout(function(){
    //ajax call here
  }, 300);
  timers.push(timeout);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜