首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在javascript中暂停递归函数3秒?

如何在javascript中暂停递归函数3秒?
EN

Stack Overflow用户
提问于 2017-07-18 07:45:47
回答 2查看 1.1K关注 0票数 0

在写这篇文章之前,我已经看到了下面提到的问题。

how-to-pause-a-settimeout-call

how-to-pause-a-settimeout-function

how-to-pause-a-function-in-javascript

delay-running-a-function-for-3-seconds

问题

下面是我想要在一段时间后暂停我的setTimeout函数的代码。那就再继续。

代码语言:javascript
复制
 typingCallback(that) {
     let total_length = that.typewriter_text.length;
     let current_length = that.typewriter_display.length;
     if (that.rewind === false) 
     {
         if(total_length  == current_length) 
         {
             // Here I want to pause this function for 3 seconds
            clearTimeout(3000);
            that.rewind = true;
         }
         else
         {
             that.typewriter_display += that.typewriter_text[current_length];
             console.log('Loop#1: ' + that.typewriter_display + " " + 'Length' + current_length);
         }
      } 
      else if (that.rewind === true)
      {
          if(current_length == 0) 
          {    
              that.rewind = false;
          }
          else
          {
              that.typewriter_display = that.typewriter_display.slice(0, -1);
              console.log('Loop#2: ' + that.typewriter_display + " " + 'Length' + current_length);
          }
      }
      setTimeout(that.typingCallback, 75, that);
   }
EN

回答 2

Stack Overflow用户

发布于 2017-07-18 07:54:49

基本上,一个简单的setTimeout应该这样做:

代码语言:javascript
复制
typingCallback(that) {
 let total_length = that.typewriter_text.length;
 let current_length = that.typewriter_display.length;
 if (that.rewind === false) 
 {
     if(total_length  == current_length) 
     {
         // Here I want to pause this function for 3 seconds
        setTimeout(that.typingCallback,3000,that);//simply set the 3 second timeout
        that.rewind = true;
        return;//dont forget to stop the function somewhere here. If not were having two recursive timeout chains... :/
     }
       //call directly
       setTimeout(that.typingCallback,75,that);// the regular timeout
票数 1
EN

Stack Overflow用户

发布于 2017-07-18 07:54:50

试试这个..。

代码语言:javascript
复制
function live() { 
    if (dead) {
        return;
    }
    // do something when alive
    setTimeout(live,speed);
} 
live();

希望这对你有用..。:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45160542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档