How to execute a function N times in 1 second

3

I need to run a function N times, but what I did so far did not work, remembering that this N times have to be evenly distributed for 1 second.

async function sendImage() {
    Console.log('teste');
}
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
    while(true){
        sendImage();
        await sleep(1000/60);
    }
}

demo();
    
asked by anonymous 28.12.2017 / 19:31

2 answers

1

Why not pass the value "N times" in the demo() function, like this:

demo(5); // executar função 5 vezes em 1 segundo

And in the demo() function receive and divide this value into 1000, which is equivalent to 1 second:

async function demo(n) {
    while(true){
        sendImage();
        await sleep(1000/n);
    }
}

It would look like this:

async function sendImage() {
    console.log('teste');
}
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo(n) {
    while(true){
        sendImage();
        await sleep(1000/n);
    }
}

demo(5); // 5 vezes em 1 segundo
  

As noted, the correct is console.log (all lowercase), otherwise the   script to run.

    
28.12.2017 / 20:03
0

To get to 1 second you need to pass the milliseconds, which equals 1000.

async function sendImage(i) {
    console.log('teste ' + Math.random());
}
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
    while(true){
        sendImage();
        await sleep(1000);
    }
}

demo();

PS: Had an error in Console.log , the correct one is console.log

    
28.12.2017 / 19:40