Reputation: 43
I'm trying to understand callbacks, so I created a test code to check async behavior.
function wait() {
while (new Date() < 2000 + new Date().getTime()){}
console.log("end");
}
console.log("start");
wait();
function clicke(){
console.log("click!")
}
document.addEventListener('click', clicke);
So I expect to logs put start
then clicks
when I do them and 2 secs later end
. But the issue is all event notifications come after start
and end
printed out.
What am I doing wrong?
Upvotes: 4
Views: 47
Reputation: 13304
Asynchronous means that a tread is running besides another thread. However your browser isn't multithreaded, it's single threaded. It will run code in the order it is presented. It will try to finish the while loop
you've created before going on to the next line. The GUI is also hooked into that thread. You are basically blocking the GUI during the while loop
ergo the page becomes unresponsive.
Additions to JavaScript were made to circumvent hanging the main thread. Ajax calls are asynchronous, because you don't want xml-files that are some 5 mb big render the browser useless during loading. Also the original setTimeout
and setInterval
allow for asynchronous operations. They don't block the thread, but run aside it.
New techniques are being developed and implemented like promises
that also allow for asynchronous call, but you can chain functions to the asynchronous object.
Asynchronous handling with an example:
function start() {
document.body.innerHTML += "<p>Started, you have ten seconds to click as much as you can.</p> ";
var callback = function(){alert("Game Over")};
document.addEventListener('click', clicke);
setTimeout('end('+callback+')', 10000); //send the callback to end the function end.
}
start();
var clicked = 0;
function clicke(){
document.body.innerHTML += "<p>Clicked: "+ (clicked++) +"</p> "
}
function end(callback)
{
document.body.innerHTML += "<p>Ended, you can no longer click.</p> ";
document.removeEventListener('click', clicke);
callback();
}
Upvotes: 2
Reputation: 1845
JavaScript is single-threaded and the while loop blocks the thread. After two seconds of busy-waiting in that while loop, it handles the events you're creating. To log a message at two seconds, do this:
setTimeout(function(){console.log("message")}, 2000);
See https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
Upvotes: 3