I want to write a code that behaves like google's translate form.
When I enter a letter in the input text-box, there is a 0.5
second delay that waits for new input. If no new input is received, the request is sent to the server which will return the results on an output text-box.
I wrote something, but it is not complete. Could you help me?!
$(document).ready(function(){
$('#source').keyup(function(){
var keyUpTime = $.now();
setTimeout(function(){
if($.now() - keyUpTime >= 500) {
sendValue($('#source').val());
}
},500);
});
});
function sendValue(str){
$.post("ajax.php",{ sendValue: str }, function(data){
$('#result_box').html(data.returnValue);
}, "json");
};
This is what I wonted:
var keyUpTime = 0;
var t = 0;
var executeAfterOneSecond = false;
$('#source').keyup(function(){
if(executeAfterOneSecond == false){
executeAfterOneSecond = true;
t = setTimeout(function(){
executeAfterOneSecond = false;
sendValue($('#source').val());
}, 600);
}
keyUpTime = $.now();
setTimeout(function(){
if($.now() - keyUpTime >= 200) {
clearTimeout(t);
executeAfterOneSecond = false;
sendValue($('#source').val());
}
},200);
});
If the interval between letters is less than 200ms, the request is not sent. If passed 600ms, and the request has not been sent, then request is automatically forwarded. If the interval between letters is more than 200ms, request is send.
Store your timeout so it can be overridden in the event of a new event, but sent off if nothing further was supplied. Simply stated:
var ajaxTimeout = null;
$('#source').on('keyup', function(e){
var val = $(this).val();
if (ajaxTimeout){
clearTimeout(ajaxTimeout);
}
ajaxTimeout = setTimeout(function(){
sendValue(val);
}, 0.5e3); // 0.5 seconds
});