Suppose, right now it is 1:04 PM. First, 10 mins slot is 1:04 PM to 1:14 PM, the screenshot will be taken at any time randomly between 1:04 PM and 1:14 PM and once we reach 1:14 PM a new slot is from 1:14 PM to 1:24 PM and a random screenshot is taken between 1:14 PM and 1:24 PM. How do I achieve this, I am a beginner and struggling to build the logic required.
I want to make changes to setTimeout to make it execute randomly any time in a span of 10 minutes, just like how Upwork screen tracker works.
Here is my code.
const uploadFiles = (img) => {
// logic
const storageRef = ref(storage,
`/screenshots/${uuidv4()}`);
uploadString(storageRef, img,
"data_url").then((snapshot) => {
console.log("Uploaded a data_url string!");
});
};
let newTimeoutId;
const screenshot = async () => {
setTimeoutId(true);
const newTimeoutId = setTimeout(async () => {
const screenshotData = await
ipcRenderer.invoke("capture");
const string = new
Buffer.from(screenshotData).toString("base64");
const img = `data:image/png;base64,${string}`;
console.log(img);
uploadFiles(img);
screenshot();
}, 600000);
};
const stopScreenshot = () => {
setTimeoutId(false);
clearTimeout(newTimeoutId);
};
CodePudding user response:
i am also really new to js, but maybe you could use Math.random.
something like this?:
Math.floor((Math.random() * 600000) 1);
it returns a number between 1 and 600000
CodePudding user response:
This should give an idea of one possible way to achieve what is desired:
Execute a function / logic at one random time, within every 10 minutes.
Code Snippet
let stopAt = 15; // for testing, setting a maximum of 15 iterations
let maxRandomDelay = 1000; // max 1 second delay for testing
// for 10 minutes, make it 10 * 60 * 1000
const resDiv = document.getElementById("rd");
resDiv.innerText = 'display at random intervals: ';
const delay = async(ms) => new Promise(res => setTimeout(() => { res(ms); }, ms));
const myTimer = () => {
delay(Math.floor(Math.random() * maxRandomDelay))
.then((r) => {
resDiv.innerText = `\n..${stopAt} (random-wait: ${r} ms).. `;
// instead of the above line, invoke your desired function here
}).then(() => {
if (stopAt-- > 0) myTimer();
})
};
myTimer();
<div id="rd" />