settimeout inside for in code example
Example 1: settimeout inside loop
//you can leave the sleep constant
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
const doSomething = async () => {
for (/*for loop statements here*/) {
//code before sleep goes here, just change the time below in milliseconds
await sleep(1000)
//code after sleep goes here
}
}
doSomething();
Example 2: javascript this in settimeout
function func() {
this.var = 5;
this.changeVar = function() {
setTimeout(() => { //Don't use function, use arrow function so 'this' refers to 'func' and not window
this.var = 10;
}, 1000);
}
}
var a = new func();
a.changeVar();