They both returned true for me, just different order:
Ok setInterval VS setTimeout:
setInterval - will run the function inside EVERY x ms. which means:
setInterval(() => {
console.log('I will run every 100ms')
}, 100)
Will run EVERY 100ms.
setTimeout - will run the function inside AFTER x ms. which means:
setTimeout(() => {
console.log('I will run after 10 seconds')
}, 10000);
will run AFTER 10 seconds.
So doing this:
let timer = setInterval(() => {
console.log('I will run every 500ms';
setTimeout(() => {
cosole.log('I will run AFTER 500ms EVERY 500ms');
}, 500);
}, 100)
The log inside setTimeout will run 500ms AFTER the first log has been triggered and will trigger every 100ms.
EDIT - Answer to user's edited question:
For clearer logs, I modified your code:
var temArr = []
var intervalOrder = 0;
var timeoutOrder = 0;
var timer = setInterval(() => {
var target = Math.random()
temArr.push(target)
intervalOrder++
console.log('ONE - SET TIMEOUT: ', {order: intervalOrder, target, tem: temArr[temArr.length - 1], result: target === temArr[temArr.length - 1]})
setTimeout(() => {
timeoutOrder++
console.log('TWO - SET TIMEOUT: ', {order: timeoutOrder, target, tem: temArr[temArr.length - 1], result: target === temArr[temArr.length - 1]}) // two
}, 500);
}, 100)
setTimeout(() => {
clearInterval(timer)
}, 1000);
Notice how TWO - SET TIMEOUT doesn't fetch the same result as ONE - SET TIMEOUT? It's because it doesn't fetch the value of that variable when it was called but it fetches ON TRIGGER which means that the value already changed because setInterval has shorter time.
What you can do for this is to call the setTiemout on a different function so it will reference its value on the parameter instead of the newly generated one.
var temArr = []
var intervalOrder = 0;
var timeoutOrder = 0;
var logSecond = (target) => {
setTimeout(() => {
timeoutOrder++
console.log('TWO - SET TIMEOUT: ', {order: timeoutOrder, target, tem: temArr[temArr.length - 1], result: target === temArr[temArr.length - 1]}) // two
}, 500);
}
var timer = setInterval(() => {
var target = Math.random()
temArr.push(target)
intervalOrder++
console.log('ONE - SET TIMEOUT: ', {order: intervalOrder, target, tem: temArr[temArr.length - 1], result: target === temArr[temArr.length - 1]})
logSecond(target)
}, 100)
setTimeout(() => {
clearInterval(timer)
}, 1000);
^^ on the snippet above, the target and result are now the same for both logs.
9 0.357113447138378 0.357113447138378 trueso two is true as you expected.