Here is a simple web page which stores unique input texts as Map keys. This is triggered the keyup
event on the text input field. In case a particular text already exists in the Map, a message “repeat” is displayed in the label with id = ‘old’. This works as expected when I type slowly but it usually displays “repeat” when I type quickly, even for first time texts. How can I fix this?
class KeyupClass {
newlabel = document.getElementById('new');
textmap = new Map();
oldlabel = document.getElementById('old');
update = (event) => {
this.newlabel.innerHTML = `new text ${event.target.value}`;
if (this.textmap.has(event.target.value)) this.oldlabel.innerHTML = 'repeat';
else {
this.textmap.set(event.target.value, this.oldlabel.innerHTML);
this.oldlabel.innerHTML = `previous text ${event.target.value}`;
}
};
constructor() {
document.getElementById('textinput').addEventListener('keyup', this.update);
}
}
new KeyupClass();
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>keyup event test</title>
</head>
<body>
<div style="display: grid">
<label>editing input updates old and new labels on each keystroke</label>
<input type="text" id="textinput" placeholder="add text here" />
<label id="old">old text</label>
<label id="new">new text</label>
</div>
</body>
</html>