Svelte测验应用中setTimeout执行时页面出现随机数字的问题求助
问题原因
你在Svelte模板里用{setTimeout(...)}的写法,会让Svelte把这个表达式的返回值(也就是setTimeout返回的定时器ID)直接渲染到DOM里,所以才会出现随机数字。
解决方案
方案一:用Svelte反应式语句处理定时器
把定时器逻辑移到<script>标签里,用Svelte的反应式声明监听questionAnswered的变化,当它变为true时自动启动定时器:
<script> const toNextQuestion = () => { currentQuestionIndex += 1; correct = undefined; questionAnswered = false; }; // 当questionAnswered为true时触发定时器 $: if (questionAnswered) { setTimeout(() => toNextQuestion(), 1000); } </script> <!-- 模板里删除原来的setTimeout代码块 --> {#if questionAnswered} <!-- 这里可以保留答题结果的提示内容,不需要定时器代码 --> {/if}
方案二:在答题完成的函数中直接启动定时器
找到你处理用户答题的函数(比如evaluateAnswer),在设置questionAnswered = true的同时启动定时器,这样完全不需要在模板里写定时器相关代码:
<script> const toNextQuestion = () => { currentQuestionIndex += 1; correct = undefined; questionAnswered = false; }; const evaluateAnswer = (selectedAnswer) => { // 这里保留你原来判断答案对错、更新分数的逻辑 // ... // 标记答题完成并启动定时器 questionAnswered = true; setTimeout(() => toNextQuestion(), 1000); }; </script>
这两种方法都能实现延迟1秒跳转的需求,同时不会把定时器ID渲染到页面上。
内容的提问来源于stack exchange,提问作者Edward
相关产品推荐
相关产品推荐

