JS减少重复的代码
在我的JavaScript文件,我书面方式一段代码数次:JS减少重复的代码
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毫秒执行。
做一个函数来包装你的代码
const callMyFunctionWithDelay = message => setTimeout(() => myFunction(message), 500);
callMyFunctionWithDelay("this is called after half a second");
callMyFunctionWithDelay("this is another message");
:你可能只是这样做复制,并让它作为输入消息。
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");
更新:如果你想增加的延迟,你只需要把循环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
也许这样?
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);
}
编辑(粗体),由不便之处:( – Ommadawn
如果您打算每次都调用相同的延迟函数,但消息是唯一发生变化的函数。如果你想要的东西更灵活,更想改变功能,消息,耽误你可以做到这一点
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 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。我不确定这是你问的,但我希望它有帮助!
多次调用同一个函数没有任何问题。 – zerkms
'setTimeout(function(){ const messages = [“这是一条消息”,“这是另一条消息”,“这是另一条消息”]; messages.forEach(m => myFunction(m)) ; },500); ' – zerkms
,你可以用一个简单的功能,像封装:'功能延迟(M){setTimeout的(函数(){ myFunction的(M); },500)}' – maioman