Try the below code.
var triggerTime;
$("#notes").keyup(function() { // notes is the id of the textarea
clearTimeout(triggerTime);
var myValue = $(this).val();
triggerTime = setTimeout(function(){
var regex = /\-([^\)]+)\-/gmi; // it gets the text between minus sign. Example: -text-
if(myValue.match(regex)){
var reference = myValue.match(regex);
$.ajax({
async: false,
type: "POST",
url: "scripts/script.php",
data: { "reference" : reference },
success: function(data) {
// I need to replace the text matched by the regex with data in the textarea.
// I need to stop the ajax calling after success or call it only if regex is matched
}
});
}
}, 3000);// Call request in 3 second
});
This is the optimized version of your code. it will wait for users to complete, and in inactivity of 3 seconds, it will generate an Ajax call.
you can change the frequency to 2000 OR 1000 (2 second and 1 second respectively).