I am sorry for the general question, but I would really like this one to be handled.
I am used to programming languages live Java or PHP, where program executes line by line, but sometimes I use javascript when it has good libraries.
The asynchronity stuff drives me nuts.
document.body.innerHTML = "";
for(var i=0;i<3;i++){
document.body.innerHTML+="Hi! ";
alert();
}
I expect this piece of code to work like this:
- Delete the whole content of the "body" tag.
- Print "Hi! "
- Invoke alert.
- Print "Hi! ".
- Invoke alert
- Print "Hi! ".
- Invoke alert.
In reality it works like this:
- Invoke alert
- Invoke alert
- Invoke alert
- Delete the whole content of the "body tag".
- Print "Hi! ".
- Print "Hi! ".
- Print "Hi! ".
How to make javascript code behave like a normal program?
Thank you!
UPDATE:
The first duplicate suggestion is not a duplicate at all. It has completely different code (I don't even use setTimeout), different task and different explaination. Even if the answer to my question is hidden there somewhere (in the comment number 56 or something like that), it is so unclear, that should not be taken as a duplicate.
The selected solution in the second duplicate suggestion simply does not work:
function b(){
document.body.innerHTML = ""; for(var i=0;i<3;i++){
document.body.innerHTML+="Hi! ";
alert();
}
}
function c(){
setTimeout(b, 1);
};
c();
So NO, NEITHER of these links are duplicates.