tags:

views:

42

answers:

2

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

    });

}
+2  A: 

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.

Marius
subjectivecheck(id) is never called when I wrap it in an anonymous function as you said.
Steven
It doesn't work.ajaxCallTimeoutID = setTimeout(function(){subjectivecheck(id)}, 1000);does not work.
Steven
I tested with alert instead of subjectivecheck, and that works. The problem has to do with subjectivecheck, not the code you posted here.
Marius
The HTML code based on is generated dynamically.
Steven
I have pasted subjectivecheck here.What's wrong with it?
Steven
A: 

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);
});
czarchaic
Sorry, it must be $("input[id^='question']").live() since the corresponding code is dynamically created.
Steven
It wouldn't be hard to change the above code to `live('keydown')`
czarchaic