最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Wait for setTimeout to complete then proceed to execute rest of the code - Stack Overflow

programmeradmin1浏览0评论
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:

  1. If if(file) is true, set sendingMessage = true (sendingMessage triggers a spinning wheel animation)
  2. Wait for 3.8 seconds and execute the content in the timeout function.
  3. 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 mands (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.

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:

  1. If if(file) is true, set sendingMessage = true (sendingMessage triggers a spinning wheel animation)
  2. Wait for 3.8 seconds and execute the content in the timeout function.
  3. 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 mands (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.

Share Improve this question edited Oct 16, 2020 at 10:51 rohanharikr asked Oct 16, 2020 at 10:37 rohanharikrrohanharikr 1,8112 gold badges20 silver badges35 bronze badges 4
  • 2 Uhm, just move the mands inside the setTimeOut's callback function? – obscure Commented Oct 16, 2020 at 10:40
  • Does this answer your question? What is the JavaScript version of sleep()? – Emiel Zuurbier Commented Oct 16, 2020 at 10:41
  • const promise1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('foo'); }, 300); }); promise1.then((value) => { console.log(value); // expected output: "foo" }); – 3squad Commented Oct 16, 2020 at 10:44
  • 1 @obscure yup this works, but the issue if file is not present it should skip the timeout function and proceed to execute the rest. If am moving the mands inside the timeout function then I would have to write the same mands again in another if block (if !file) but I am just trying to avoid writing duplicate code. But feel like I can make this a function and call it both the places? What do you think? – rohanharikr Commented Oct 16, 2020 at 10:46
Add a ment  | 

3 Answers 3

Reset to default 6

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();
}

You can't achieve this directly. You have to wrap your timeout function into a promise and await for the result inside an async function.

let file = true

function asyncTimeout(resolver){
    return new Promise(resolver) 
}

async function sendMessage(){

        console.log("Before setTimeout")

    if(file){
    
      await asyncTimeout((resolve, reject) => {
        setTimeout( function() {
          console.log("Timeout finished!")
          resolve()
        }, 3800) 
      })
         
    }
    
    console.log("After setTimeout")
}


sendMessage()

Here is a fiddle: https://jsfiddle/38rwznm6/

You can use promise here, your example is to plex, so I will show smaller

function sleep(time) {
  return new Promise(resolve=>setTimeout(resolve, time));
}

async function run() {
  console.log(1);
  await sleep(1000);
  console.log(2);
}

run();

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>