I have an array (myArray) created from the keys of an object (myObject). I get input from user (userInput) and compare with myArray to get common phrases (intersect). I select the longest common phrase (being a property name in myObject) and then get its value and display in myOuput "else" statement. If the phrase has no corresponding value, it will simply display what the user typed in myOutput "if" statement. This works fine, except that the regex expression results in latency in delivery, especially with a huge size of myObject. I want to implement a setTimeout that gets reset each key press, and I want to run my logic some 250ms or so, after input so that it is not running on every single keypress. I learned about debounce, but I don't now how to implement it. I need help.
Unfortunately the links suggested could not address my case specifically; in my case, the debounce function needs to be triggered with oninput event rather than onmousemove event. Below is a debounce function I got online--I want the timeout to be something like 250ms after every keypress rather than instant. Try typing "how are you" to see how it works. Can someone show me how to adapt the debounce function to my situation? Thanks.
function debounce(func, wait, immediate) {
let timeout;
return function () {
const context = this,
args = arguments,
later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
myObject = {
"good morning": "ma be dehe",
"good": "bao",
"morning": "suazi",
"go": "doi",
"i": "mu",
"how are you": "dai ze de",
};
function getValue() {
const userInput = document.getElementById("myInput").value.trim()
.toLowerCase();
const myArray = Object.keys(myObject);
const intersect = myArray.filter((word) =>
userInput.match(new RegExp("\\b" + word + "\\b"))
);
var lgth = 0;
var longest;
for (var i = 0; i < intersect.length; i++) {
if (intersect[i].length > lgth) {
var lgth = intersect[i].length;
longest = intersect[i];
}
}
if (!(longest in myObject)) {
document.getElementById("myOutput").innerHTML = userInput;
} else {
document.getElementById("myOutput").innerHTML = myObject[longest];
}
}
<textarea id="myInput" placeholder="type here..." oninput="getValue()"></textarea> <br>
<textarea id="myOutput"></textarea>