【问题标题】:How do I print each character of a string but with 1s of delay in JavaScript?如何打印字符串的每个字符但在 JavaScript 中有 1 秒的延迟?
【发布时间】:2020-11-05 05:35:27
【问题描述】:

我想在屏幕上打印“Hello World”,但每个字符一个一个,延迟 1 秒。我使用了 setInterval() 函数,但它不起作用。为什么?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test</title>
</head>
<body>
    <script>
        function type(){
            var text = "Hello World!";
            var i;
            var o = "";
            for(i = 0;i < text.length;i++){
            o += text[i]
            document.write(o[i])
            
            }
        }

    var exe = setInterval(type(), 1000);
    </script>
</body>
</html>

【问题讨论】:

    标签: javascript settimeout delay


    【解决方案1】:

    你的代码有很多错误,我不知道从哪里开始......

    很抱歉这样说,但这里有一个更简洁的版本,请注意 cmets:

    const text = "Hello World!";
    
    // the timer reference
    let timer;
    
    // the current index
    let i = 0;
    
    // you don't need a for loop in setInterval, the function itself is aleady called in iterations, just treat it as a loop iteration.
    function type() {
    
      // print the current charater with current index
      document.write(text[i]);
      
      // increase the index
      i++;
      
      // if the index reaches the maximum text length, cease the timer
      if(i >= text.length) 
        clearInterval(timer);
    }
    
    // pass in function, instead of calling it
    timer = setInterval(type, 1000);

    【讨论】:

      【解决方案2】:

      我们只需将字符串拆分为数组,然后在插入页面时删除第一个元素。

      当我们的数组中没有元素时,我们停止计时器。

      let str = 'Hello world'.split('');
      
      const interval = setInterval(() => {
        document.write(str[0]);
        str = str.slice(1);
        
        if (!str.length) {
          clearInterval(interval);
        }
      }, 1000);

      【讨论】:

        【解决方案3】:

        我对你的逻辑做了一些改动。

        type() 函数只会进行字符打印。

        intialize 起始位置为0text

        itext.length 相同时clearInterval

        <!DOCTYPE html>
        <html lang="en">
        
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <title>Test</title>
        </head>
        
        <body>
          <script>
            var text = "Hello World!";
            var i = 0;
            var o = "";
        
            function type() {
              o += text[i];
              document.write(o[i]);
              i++;
              if (i == text.length) {
                clearInterval(interval);
              }
            }
            var interval = window.setInterval(type, 1000);
          </script>
        </body>
        
        </html>

        【讨论】:

          【解决方案4】:

          <!DOCTYPE html>
          <html lang="en">
          <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <meta http-equiv="X-UA-Compatible" content="ie=edge">
              <title>Test</title>
          </head>
          <body>
              <script>
                  function type(){
                      var text = "Hello World!";
                      var o = "";
                      for(let i = 0;i < text.length;i++){
                      o += text[i];
                      setTimeout(()=> document.write(o[i]), i*1000);
                    }
                  }
              type();
              </script>
          </body>
          </html>

          【讨论】:

            【解决方案5】:

            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <meta http-equiv="X-UA-Compatible" content="ie=edge">
                <title>Test</title>
            </head>
            <body>
                <script>
                    var i = 0
                    var o = "";
                    var text = "Hello World!";
                    function type(){
                        if(i < text.length){
                            o += text[i]
                            document.write(o[i])
                            i++
                            setTimeout(type, 1000)
                        }
                    }
            
                    setTimeout(type, 1000)
                </script>
            </body>
            </html>

            【讨论】:

              【解决方案6】:
                  <!DOCTYPE html>
              <html lang="en">
              <head>
                  <meta charset="UTF-8">
                  <meta name="viewport" content="width=device-width, initial-scale=1.0">
                  <meta http-equiv="X-UA-Compatible" content="ie=edge">
                  <title>Test</title>
              </head>
              <body>
                
              </body>
                <script>
                  var i=0;
                   var text = "Hello World!";
                     
              
                  var exe = setInterval(function (){if (i<text.length)
                               document.write(text[i])
                          
                    
                          i++;}, 1000);
                  </script>
              </html>
              

              【讨论】:

              • 请在您的回答中添加一些解释。
              • 原代码中不需要使用for循环。打印的当前字符的计数器应该在全局范围内而不是在函数范围内可用。添加 if 条件,直到文本有字符,打印当前字符。虽然应该有一个 else 条件来清除这个问题的其他答案所提供的间隔。
              【解决方案7】:

              大概是这样的吧?

              const word = "Hello World";
              
              function printWord(str) {
                if (typeof str === "string") {
                  let curIndex = 0;
                  const interval = setInterval(() => {
                    if (curIndex < str.length) {
                      console.log(str[curIndex]);
                      curIndex++;
                    } else {
                      clearInterval(interval);
                    }
                  }, 1000);
                }
              }
              
              printWord(word);
              

              【讨论】:

                【解决方案8】:

                 var interval = null
                 function type(){
                            var text = "Hello World!";
                            var i = 0;
                            interval = setInterval( () => {
                             if( i === text.length -1) {
                               clearInterval(interval);
                               
                               }
                               document.write(text[i]);
                             console.log(text[i++]);
                             
                             }, 1000)    
                  }
                  
                  type()

                【讨论】:

                  【解决方案9】:

                  我们可以使用闭包的概念,将要打印的字符的索引作为闭包变量来维护。

                  每次执行间隔回调函数时,索引都会递增,内部函数会从词法范围中获取索引的当前值。

                  那么一旦text的长度等于索引,就清空区间:

                  <!DOCTYPE html>
                  <html lang="en">
                  
                  <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <meta http-equiv="X-UA-Compatible" content="ie=edge">
                    <title>Test</title>
                  </head>
                  
                  <body>
                    <script>
                      function type(text, idx) {
                        document.write(text[idx]);
                      }
                      function start() {
                        //The index to keep track of and increment from the timer
                        let idx = 0;
                  
                        //The text to iterate
                        const text = "Hello World!";
                  
                        //Set up the interval with a callback and form a closure
                        const id = setInterval(() => {
                  
                         //Refers to the text and idx from the lexical scope
                          type(text, idx++);
                  
                          //Once the index has reached the length of the text
                          if (idx === text.length) {
                  
                            //clear the interval id
                            clearInterval(id);
                  
                          }
                        }, 1000);
                      }
                  
                      //Invoke the main function
                      start();
                    </script>
                  </body>
                  
                  </html>

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2016-10-29
                    • 2022-10-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2022-12-24
                    • 1970-01-01
                    • 2022-01-16
                    • 2020-02-01
                    相关资源
                    最近更新 更多