I have this problem that came up and I realized that I don't understand callbacks nearly as good as I should.
The way it's worded makes me think that I need to make it a set interval, but then you see that there is the syntax of "function randomExecution(callback) {}" and that really trips me up.
On top of all of this, this problem really makes me realize how inefficient I am at breaking down a problem into smaller parts. I see the "make sure it's on average about 1~2 times per minute" and I just get lost.
(I get that i can be less than 10 seconds that I have the min set to, but I'm pretty lost here and that was my only solution to make it so it doesn't get called within ten seconds)
What am I doing wrong here?
Also, any advice on how to approach questions like this would be greatly appreciated.
Cheers!
The Problem:
function randomExecution(callback) {
// start an interval that executes `callback()` at random intervals
// make sure it's on average about 1~2 times per minute
// make sure it doesn't execute twice within 10 seconds
}
My attempt:
function randomExecution(callback) {
const min = 10
const max = 120
const random = Math.floor(Math.random() * (max - min + 1) + min)
// callback = console.log('Wait for ' + random + ' seconds')
return random
}
setInterval(console.log(`hi, after ${randomExecution()} seconds`) , randomExecution)
question from:
https://stackoverflow.com/questions/65903012/javascript-create-function-that-executes-a-callback-function-at-random-interval 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…