The functions planned to start with setTimeoutare executed in the main loop, outside the main code that created them.
To handle errors, put try-catchinside the handler setTimeout:
setTimeout(function () {
try {
throw new Error('error!');
} catch (e) {
console.error(e);
}
}, 300)
If you need access to an object Errorfrom a block called setTimeout, use Promises :
const promise = new Promise((resolve, reject) => {
setTimeout(function () {
try {
throw new Error('error!');
} catch (e) {
reject(e)
}
}, 300)
})
promise
.then(result => console.log("Ok " + result))
.catch(error => console.error("Ouch " + error))
- Promise. delay(ms) :
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
delay(300).then(myFunction).catch(handleError)