Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

asynchronous - Javascript: Create Function that executes a callback function at random intervals on average of 1~2 times per minute

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem lies in the fact that you use the function SetInterval, which, as the name suggests, is used to call a specified function repeatedly after a fixed interval. A better approach would be to create a recursive loop with SetTimeout, where your code would look like this:

function example() {
    console.log('See you soon!')
}

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

    const min = 30
    const max = 60
    var random = Math.floor(Math.random() * (max - min + 1) + min)

    setTimeout(function() {
        callback();
        randomExecution(callback);
    }, random * 1000);
}

randomExecution(example)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...