JS减少重复代码

JS reduce repeated code

在我的 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之外并制作一个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);

也许是这个?

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

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

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

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

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

它将 return 超时 ID,以防您需要使用 cancelTimeout 取消它。然后您可以将代码简化为以下内容:

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

你的意思是这样的吗?

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),其中 delay 是一个包含您想要的延迟的整数(以防您不总是想要 500)。

PS。我不确定这是否是你问的,但我希望它能有所帮助!