var speed = 200,
len = 0;
if (e in know) {
function typing() {
if (len < know[e].length) {
if (len === know[e].length - 1) {
t.innerHTML = know[e];
g = d.getAttribute("data-bottom") ? d.getAttribute("data-bottom") : 0;
if (parseInt(g) < ((d.scrollHeight - t.offsetTop) - p.clientHeight) + 10) d.scrollTo(0, d.scrollHeight);
else alert("new message");
}
len++;
setTimeout(typing, speed);
}
}
typing();
setTimeout vs setInterval code...
var setIn = setInterval(() => {
if (len < know[e].length) {
if (len === know[e].length - 1) {
clearInterval(setIn);
t.innerHTML = know[e];
g = d.getAttribute("data-bottom") ? d.getAttribute("data-bottom") : 0;
if (parseInt(g) < ((d.scrollHeight - t.offsetTop) - p.clientHeight) + 10) d.scrollTo(0, d.scrollHeight);
else alert("new message");
}
len++;
}
}, speed)
I'm trying to make a reply bot that starts typing after 1 seconds and that will reply back at the speed of the String.length and they both did the same thing but someone once told me using setTimeout is bad practice, but I need them to run that exact way. If there is another work around for it I'm open to all suggestions, Thanks in advance.
You can have multiple approaches:
setIntervalsetTimeoutwindow.requestAnimationFrameIf you need to wait for 1 second, then you must have a setTimeout and inside, I encourage you to use the 3rd option if you want to save performance, but combining setTimeout with setInterval is an available option. The use of them is not a bad practice in general, just in particular cases.
You can use async/await to emulate typing and create delays:
//
// Async timeout function
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
//
// Bot typing function
const runBot = text => {
// Use promises
return new Promise(async (resolve, reject) => {
// DOM
const div = document.getElementById('text');
// Create chars array
const chars = text.split('');
// Wait 1 sec before typing
await timeout(1000);
// Type text
while(chars.length) {
// Put one char at iteration
div.innerHTML += chars.shift();
// Wait some amount
await timeout(100);
}
// Add new line to the text box
div.innerHTML += '<br>'
// Finish function
return resolve();
});
}
//
// Text typing runner and button controller
const typeText = async text => {
// DOM
const button = document.querySelector('button');
// Disable button
button.disabled = true;
// Run bot and wait till it finishes
await runBot(text);
// Enable button
button.disabled = false;
}
<div id="text" style="padding:10px;border:1px solid #000"></div>
<button onClick="typeText('This is demo text!')">Start bot</button>