Forum Discussion
Setting Data Entry Object Focus & Auto-Advance to Next Slide When Correct Value is Entered
- 7 months ago
See the attached .story file. Let me know if it worked for you.
Just tried to preview the entire project story file again. Now the Search Text Entry object does not have focus and requires the learner to click the field to begin typing the word Profile. Also tried previewing only the single scene itself with the same result. The www.w3schools.com reference states:
* The Window setTimeout() method is executed only once.
* If you need repeated executions, use setInterval() instead.
* Use the clearTimeout() method to prevent the function from starting.
Do I need to use setInterval() instead and stop the execution after X milliseconds? Thoughts?
I was not able to replicate this issue. In your case, it could be that the browser hasn't finished rendering the input field when setTimeout(..., 100) runs. If the input isn't fully interactive when focus() is called, the focus might not take effect. The current execution stack is cleared, but that still might be before the input is ready to be focused. Try increasing the delay from 100ms to 200ms.
Set Timeout vs Set Interval
- More Efficient → setTimeout runs once, while setInterval keeps running until stopped. Since you only need to focus the input a few milliseconds later, a single delay is usually enough.
- No Need for Cleanup → setInterval requires clearInterval() to stop unnecessary retries, whereas setTimeout doesn't need extra handling.
- Simpler & Less Processing → Running setInterval repeatedly for something that succeeds on the first or second attempt isn't efficient.
- Use setInterval only if there’s a high chance the input won’t be ready within a fixed delay (e.g., dynamically loaded content). In that case, you need multiple retries.
Set Interval Example:
var input = document.querySelector('.acc-textinput');
function focusWithInterval(maxRetries = 3, intervalTime = 100) {
let attempts = 0;
let intervalId = setInterval(() => {
input.focus();
if (document.activeElement === input) {
console.log("Input is in focus!");
clearInterval(intervalId);
} else {
attempts++;
console.log(`Focus attempt ${attempts} failed. Retrying...`);
if (attempts >= maxRetries) {
clearInterval(intervalId);
console.log("Failed to focus input after multiple attempts.");
}
}
}, intervalTime);
}
focusWithInterval(3, 100);
input.addEventListener('input', function() {
var inputValue = input.value;
setVar('WordProfile_SC', inputValue);
console.log(`Updated variable: WordProfile_SC = ${inputValue}`);
});
While this works (logs show that the input is always focused on the first attempt after a 100ms delay), it feels like overkill and somewhat redundant. I suggest sticking with setTimeout for simplicity.