I am getting a javascript error in the console, which I would really like to understand. I have removed all extraneous code, leaving just an 11 line webpage. The page does work as expected, but with an error. The error given on the Chrome console is
VM1286:1 Uncaught SyntaxError: Unexpected identifier 'Promise'
This is the file test.html, I am opening the file in Chrome locally. (file://Users/Timeto/test.html) this is the code:
<!DOCTYPE html>
<html>
<head>
<script>
var asyncFunc;
asyncFunc = async() => {
console.log("called the async func");
}
window.addEventListener('load', function () {
window.setTimeout(asyncFunc(),1000);
});
</script>
</head>
<body>
</body>
</html>
I expected the console log message after 1 second of page load, which it does do correctly.
So why and where from comes this error? And if appropriate how to eliminate?
2
Answers
You should wrap
asyncFunc
inside an anonymous function like this:First of all you are using
var
which is not recommended, second thing you pass the function in the setTimeout function but instead you are running it, it should be likewindow.setTimeout(async () => asyncFunc(),1000);