JS减少了重复的代码

时间:2017-08-08 22:04:05

标签: javascript reusability code-readability

在我的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毫秒。

5 个答案:

答案 0 :(得分:3)

更新:如果您想要增量延迟,只需将循环置于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);

答案 1 :(得分:1)

也许这个?

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

答案 2 :(得分:1)

如果您每次都要以相同的延迟调用相同的函数,但该消息是唯一发生变化的事情。你可以这样做:

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

答案 3 :(得分:1)

创建一个函数来包装您正在复制的代码,并让它将消息作为输入。

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

如果您需要使用cancelTimeout取消超时ID,它将返回超时ID。然后,您可以将代码减少到以下内容:

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

答案 4 :(得分:1)

你是说这样的意思吗?

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。我不确定这是不是你问的但我希望它有所帮助!