Reputation: 727
Let's say I have the following Javascript code:
let lastTime = new Date().getTime();
for (let i = 0; i < 10; i++) {
const differenceOfTime = ((new Date()).getTime() - lastTime);
lastTime = new Date().getTime();
if ( differenceOfTime > 100 ){
console.log('Hello')
}
}
This code measures the difference of time between the current loop and the last one, if it's bigger than 100 milliseconds it prints Hello
. In this case, it'll never print Hello
because the difference of time here is never bigger than 100 milliseconds.
Let's say now that I have a different Javascript code as following:
async function executeAsync(){
let lastTime = new Date().getTime();
for (let i = 0; i < 10; i++) {
await sleep(200)
const differenceOfTime = ((new Date()).getTime() - lastTime);
lastTime = new Date().getTime();
if ( differenceOfTime > 100 ){
console.log('Hello')
}
}
}
executeAsync()
function sleep(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, time);
});
}
In this snippet it will print Hello
10 times since the difference of time between the last loop and the current one is bigger than 100 milliseconds in all loops.
The problem is that I'd like to make it in a way that I'll print Hello
if nothing happens after 200 milliseconds. I'd like something like the following pseudocode:
let lastTime = new Date().getTime();
for (let i = 0; i < 10; i++) {
const differenceOfTime = ((new Date()).getTime() - lastTime);
lastTime = new Date().getTime();
if ( differenceOfTime > 100 ){
setTimeoutThatExecutesOnlyIfNoNewMessageArrivedAfter(() => {
console.log('Hello')
}, 200)
setTimeout()
}
}
I'd like to make this last snippet to print Hello
only once after the last loop iteraction. I know I could use the last index of the loop to solve this problem. But they're just examples and in my real case scenario those messages arrive as random messages (it's not inside a loop), so there's no last index to be used. I'd need a different approach and that's why I thought about a timeout that executes only after no new messages arrive. Is there any Javascript function I can use in order to solve this problem? How can I print Hello
after 200 milliseconds have passed with no new looop iteractions?
Upvotes: 0
Views: 231
Reputation: 11126
setTimeout
returns an ID that you can use to cancel the timeout (using clearTimeout(ID)
). If you receive a message in time, cancel the timeout and re-start it to wait for the next message. If no next message is received, let the timeout run and print your message.
Something like this might be what you're after:
async function executeAsync(){
let lastTime = new Date().getTime();
let timeout = null;
for (let i = 0; i < 10; i++) {
console.log('Received Message');
if (timeout) { clearTimeout(timeout); }
timeout = setTimeout(() => console.log('Hello'), 200)
await sleep(199)
}
}
executeAsync()
function sleep(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, time);
});
}
Upvotes: 1