【问题标题】:Splitting text area value into array then loop and run function将文本区域值拆分为数组然后循环并运行函数
【发布时间】:2021-11-11 20:25:02
【问题描述】:

我正在尝试:

  • 从文本区域获取输入
  • 拆分成一个字符串数组,每一行都是该数组中的一个元素
  • 遍历此数组的每个元素,运行一个使用当前元素中文本的函数,然后等待 5 秒,然后进入下一个循环迭代/元素。

不幸的是,到目前为止我的所有尝试都没有奏效,我是 JS 的初学者,所以我正在使用 sn-ps 并在这里尽力而为:

// var LS = document.querySelector('textarea').value().split('\n');
for (let i in LS) {
   setTimeOut(function(i),5000);
}

【问题讨论】:

  • setTimeout 的第一个参数必须是函数引用,而不是函数调用。

标签: javascript arrays text


【解决方案1】:

setTimeout() 的第一个参数必须是要调用的函数。您正在立即调用该函数。

如果您希望它们间隔 5 秒运行,请将超时值乘以 i。超时是从您调用 setTimeout 时开始计算的,而不是从前一个函数运行时开始计算的。

for (let i in LS) {
    setTimeout(() => yourFunction(LS[i]), i * 5000);
}

【讨论】:

    【解决方案2】:

    textInput = document.getElementById("theText");
    textArray = textInput.value.split(/\n/g);
    
    
    
    
    const delayLoop = (fn, delay) => {
      return (line, i) => {
        setTimeout(() => {
          useTheText(line);
        }, i * 5000);
      }
    };
    
    
    
    function useTheText(line){
      console.log(line);
    }
    
    const handleClick = () => {
    textInput.value.split(/\n/g).forEach(delayLoop(useTheText, 500));
    
    }
    <textarea id="theText" name="theText"
              rows="5" cols="33">
    It was a dark and stormy night...
    second line
    line 3
    </textarea>
    
    <div>
    <button onClick="handleClick()">process</button>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      相关资源
      最近更新 更多