Javascript 减少重复代码
在我的JavaScript文件中,我多次编写一段代码:Javascript 减少重复代码,javascript,reusability,code-readability,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"); }, 5
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
之外,然后开始一段生活:
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=[“这是一条消息”、“这是另一条消息”、“这又是另一条消息”];
对于(变量i=0;i
工作片段
var msgs=[“这是一条消息”、“这是另一条消息”、“这又是另一条消息”];
对于(变量i=0;i
也许是这个
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);
}
array=[“这是一条消息”,“这是另一条消息”,“这是另一条消息”
再次发送消息“];
对于(i=0;i如果您每次都要以相同的延迟调用相同的函数,但消息是唯一会更改的内容。您可以这样做:
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);
}
如果您需要使用cancelTimeout
取消超时,它将返回超时id。然后您可以将代码缩减为以下内容:
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)
另外,我不确定这是否是您所要求的,但我希望它能有所帮助!多次调用同一个函数没有错。setTimeout(function(){const messages=[“这是一条消息”,“这是另一条消息”,“这又是另一条消息”];messages.forEach(m=>myFunction(m));},500);
您可以用一个简单的函数进行封装,例如:函数延迟(m){setTimeout(function(){myFunction(m);},500)}
编辑(粗体),很抱歉给您带来不便:(@Ommadawn Updated answer.Check。另外,没有必要将myFunction的消息/参数保留在setTimeout内,与setTimeout的作用域相同fine@przemo_li对不起,我不明白那部分。这怎么写得好?编辑(粗体),很抱歉给您带来不便:(@Ommadawn Simple fix.updated.Edited(粗体),很抱歉给您带来不便:(