【问题标题】:JS reduce repeated codeJS减少重复代码
【发布时间】:2017-08-08 22:04:05
【问题描述】:

在我的 JavaScript 文件中,我多次编写一段代码:

setTimeout(function() {
   myFunction("this is a message");
}, 500);

setTimeout(function() {
   myFunction("this is another message");
}, 500);

setTimeout(function() {
   myFunction("this is another message again");
}, 500);
...

所以,我想避免一直重写 setTimeout。

还有其他方法可以压缩代码并制作出更好的可读性吗?

谢谢!

编辑:我的目标不是按顺序启动“myFunction”。我的目标是,当我调用 myFunction 时,它总是延迟 500 毫秒才能执行。

【问题讨论】:

  • 多次调用同一个函数没有错。
  • setTimeout(function() { const messages = ["this is a message", "this is another message", "this is another message again"]; messages.forEach(m => myFunction(m)); }, 500);
  • 你可以用一个简单的函数来封装,比如:function delay(m){ setTimeout(function() { myFunction(m); }, 500)}
  • 已编辑(粗体),不便之处敬请见谅 :(
  • @Ommadawn 更新了答案。检查。

标签: javascript reusability code-readability


【解决方案1】:

更新:如果您想要增加延迟,您只需将循环放在setTimeout 之外并制作一个 IIFE:

var msgs = ["this is a message", "this is another message", "this is another message again"];
for (var i = 0; i < msgs.length; i++)
  (function (idx) {
    setTimeout(function () {
      myFunction(msgs[i]);
    }, 500 * i);
  })(i);

工作片段

var msgs = ["this is a message", "this is another message", "this is another message again"];
for (var i = 0; i < msgs.length; i++)
  (function(idx) {
    setTimeout(function() {
      myFunction(msgs[idx]);
    }, (500 * i));
  })(i);

function myFunction(msg) {
  console.log(msg);
}

无论如何,上面的代码都会在第 500 毫秒内执行函数。结合三者:

setTimeout(function() {
   myFunction("this is a message");
   myFunction("this is another message");
   myFunction("this is another message again");
   // ...
}, 500);

上面的代码和这个没有区别。但是如果你想让代码看起来不错,你可以使用循环和数组:

setTimeout(function() {
   var msgs = ["this is a message", "this is another message", "this is another message again"];
   msgs.forEach(function (msg) {
       myFunction(msg);
   });
}, 500);

【讨论】:

  • 另外,也不需要在 setTimeout 中将消息/参数保存到 myFunction,与 setTimeout 相同的范围就可以了
  • @przemo_li 抱歉,没看懂那部分。这怎么能写得好?
  • 已编辑(粗体),不便之处敬请见谅 :(
  • @Ommadawn 简单修复。更新中。
【解决方案2】:

创建一个函数来包装你复制的代码,并让它接受一条消息作为输入。

function delayMessage(msg) {
    return setTimeout(() => {
        myFunction(msg);
    }, 500);
}

如果您需要使用cancelTimeout 取消它,它将返回超时 id。然后您可以将代码简化为以下内容:

delayMessage("this is a message");
delayMessage("this is another message");
delayMessage("this is another message again");

【讨论】:

    【解决方案3】:

    如果您要每次都以相同的延迟调用相同的函数,但消息是唯一改变的东西。你可以这样做:

    const callMyFunctionWithDelay = message => setTimeout(() => myFunction(message), 500);
    
    callMyFunctionWithDelay("this is called after half a second");
    callMyFunctionWithDelay("this is another message");
    

    如果您想要更灵活的东西并想要更改功能、消息和延迟,您可以这样做

    const callWithDelay = (fn, message, delay) => setTimeout(fn.bind(null, message), delay);
    
    callWithDelay(myFunction, "this is called after half a second", 500);
    callWithDelay(myFunction, "this is gets called after 1 sec", 1000);
    

    【讨论】:

      【解决方案4】:

      你的意思是这样的吗?

      function myTimeout(msg, delay = 500) {
        setTimeout(function () {
          myFunction(msg);
        }, delay);
      }
      
      function myFunction(msg){ 
        console.log(msg)
        // or do something else ..
      }
      

      所以现在你可以拨打myTimeout('message'),它会延迟500。 或者你可以打电话给myTimeout('message', delay),其中延迟是一个整数,带有你想要的延迟(如果你不总是想要500)。

      PS。我不确定这是否是您所要求的,但希望对您有所帮助!

      【讨论】:

        【解决方案5】:

        也许是这个?

        array = ["this is a message","this is another message","this is another 
        message again"];
        
        for (i=0;i<array.length;i++) {
            setTimeout(function() {
                 myFunction(array[i]);
            }, 500);
        }
        

        【讨论】:

        • 已编辑(粗体),不便之处敬请见谅 :(
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-30
        • 2016-07-24
        • 1970-01-01
        • 2020-12-25
        • 2016-01-12
        • 1970-01-01
        相关资源
        最近更新 更多