javascript - Wait for setTimeout to complete then proceed to execute rest of the code
问题描述
function sendMessage(){
...
if(file){
sendingMessage = true;
setTimeout(() => {
sendingMessage = false;
messages = [...messages, chatmessage];
}, 3800)
}
chatmessage = '';
inputRef.focus()
updateScroll();
}
Right now when this function is called, chatmessage
is first set to an empty string, etc. then the code in the timeout function is executed which is the corect behaviour. However, is there a way make setTimeout synchronous?
This is the behaviour I want:
- If
if(file)
is true, setsendingMessage = true
(sendingMessage triggers a spinning wheel animation) - Wait for 3.8 seconds and execute the content in the timeout function.
- Only then, set
chatmessage
to empty string, etc (rest of the code)
Edit 1:
I can just move the code inside the timeout function but the issue is in my case, if file
is not present, it should just skip the timeout function alltogether. Then I would have to write another if block to check if the file is not present to execute the same commands (duplicate code). Another way to solve this would be to put the same code in a function and call it both places but feel like its not the ideal way to go and creating a function to change the value of three variables seems like overkill.
解决方案
You could make use of a Promise
to wait for 3 seconds before executing the code.
For this to work, create a function that returns a promise which resolves after 3 seconds.
function wait(seconds) {
return new Promise(resolve => {
setTimeout(resolve, seconds * 1000);
});
}
Then inside the sendMessage
function, call this function, passing in the number of seconds you want to wait. When the promise returned by this wait
function resolves, execute the code that you want to execute after wait time is over.
Following code shows an example of how you coulc call wait
function inside sendMessage
function.
async function sendMessage() {
...
if(file){
sendingMessage = true;
await wait(3); // wait for 3 seconds
sendingMessage = false;
messages = [...messages, chatmessage];
}
chatmessage = '';
inputRef.focus()
updateScroll();
}
推荐阅读
- javascript - 重新附加 daterangepicker() 构造函数时,apply.daterangepicker 事件停止触发
- java - 如何根据特定日期获取所有数据?
- airflow - 在 BigQueryOperator 中添加参数作为 template_fields
- javascript - 如何在javascript中的新型匿名函数中访问此关键字
- python - 如何使第一行变成第二级MultiIndex
- python - 这段代码实际上是否具有二次复杂度?
- python - 使用 pyspark(查询)从 Hadoop 中删除文件
- ruby-on-rails - 将 cookie 传递到地理编码器
- php - 使用 php 变量时无法执行 SQL 更新
- php - 使用 PHP 的 HTML 到 PDF 转换器