const generateTimeMs = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
/**
* A generator which can generate numbers based on settings
*
* @param {number} min - min timer value, unit ms
* @param {number} max - max timer value, unit ms
* @param {number} minDiff - ensure that max - min > minDiff always true
* @returns
*/
function* RCTimer(min, max, minDiff) {
let invalidate = min + minDiff > max
if (invalidate) {
return new Error(`min value + minDiff value should less than max value`)
}
while (!invalidate) {
const firstTimer = generateTimeMs(min + minDiff, max)
yield firstTimer
const secondTimer = generateTimeMs(min, firstTimer - minDiff)
yield secondTimer
}
}
const gen = RCTimer(1000, 4000, 2000)
let count = 0
while (count < 3) {
count++
console.log(`Round ${count}: `)
const firstTimer = gen.next()
console.log(`firstTimer: ${JSON.stringify(firstTimer)}`)
const secondTimer = gen.next()
console.log(`secondTimer: ${JSON.stringify(secondTimer)}`)
}
/**
* Round 1:
firstTimer: {"value":3365,"done":false}
secondTimer: {"value":1347,"done":false}
Round 2:
firstTimer: {"value":3181,"done":false}
secondTimer: {"value":1075,"done":false}
Round 3:
firstTimer: {"value":3682,"done":false}
secondTimer: {"value":1672,"done":false}
*/
标签:secondTimer,Generator,min,max,create,Javascript,value,minDiff,firstTimer From: https://www.cnblogs.com/Answer1215/p/17840795.html