我希望在数组中的每个对象之间休眠或等待php之类的随机时间
sleep(rand(10,300));
然后console.log
var array1 = ['msg1', 'msg2', 'msg3'];
像这样
msg3 然后等待50秒
我没有尝试超时,但是问题是每50秒发送3个对象 我要在数组随机时间内foreach对象
mycode
var array1 = ['msg1', 'msg2', 'msg3'];
array1.forEach(function(element) {
setTimeout(function(){
console.log(element);
}, 5000);
});
答案 0 :(得分:0)
您的代码将立即调用所有setTimeout
。相反,您可以将这些呼叫链接起来,如下所示:
var array1 = ['msg1', 'msg2', 'msg3'];
console.log("Wait for it...");
(function loop(arr) {
if (!arr.length) return; // all done!
setTimeout(() => {
console.log(arr[0]);
// Only after having output this array value, proceed with the next timeout:
loop(arr.slice(1));
}, 500 + Math.floor(Math.random() * 5000)); // Provide some randomness
})(array1); // Immediately invoked function expression (IIFE)
答案 1 :(得分:0)
下面是一个随机setTimeout
的示例:
const arr = ['msg1', 'msg2', 'msg3'];
function loop(arr) {
// Deconstruct the array into the first
// element, and the rest
const [head, ...tail] = arr;
// if the array isn't empty
if (head) {
// Grab a random time between 1 and 10 seconds
const time = Math.floor(Math.random() * (10 - 1) + 1) * 1000;
console.log(head, time);
// Call the function again with the remaining
// array (tail), after `time`
setTimeout(() => loop(tail), time);
}
}
// Call `loop` with a copy of the array
loop([...arr]);
答案 2 :(得分:0)
如果您的环境支持async/await
,则可以:
const time = 50 // base seconds
const randomTime = () => Math.floor(Math.random() * time * 1000) // miliseconds
const messages = ['msg1', 'msg2', 'msg3']
function delayedMessage(msg, miliseconds) {
return new Promise(resolve => {
setTimeout(() => {
console.log(msg, miliseconds)
resolve()
}, miliseconds)
})
}
async function logMessages(msgArr) {
for (const index in msgArr) {
await delayedMessage(messages[index], randomTime())
}
}
logMessages(messages)