I’m trying to iterate over a string, calling a function on each letter but with a gap in between each execution (to run keydown and keyup animations for an on-screen keyboard typing a word).
I am looping through the string and awaiting and async press
function, which works perfectly on Windows and Android, but on iOS the loop stops after the first iteration (press
is called only for the first character).
const type = async (text: string) => {
const characters = text.split("");
setTyped("");
await delay(500);
for (const character of characters) {
setTyped((prev: string) => prev + character);
await press(character, 100);
await delay(100);
}
};
press
changes state with a delay.
const press = async (key: string, duration: number) => {
pressDown(key);
await delay(duration);
pressUp(key);
};
const pressDown = (key: string) => {
setPressed(key);
};
const pressUp = (key: string) => {
setPressed(null);
};
I have also tried a recursive option, but it also does not work on iOS.
const type = async (text: string) => {
if (text.length === 0) return;
setTyped((prev) => prev + text[0]);
await press(text[0], 100)
.then(() => {
return delay(100);
})
.then(() => {
type(text.slice(1));
});
};
Is this a security feature of iOS or is there an error in my code? Is there any way around it – or any better way to loop through a list and call a function for each object on a timed interval?
Thanks!
bevans is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.