Daniel Bejan
Daniel Bejan

Reputation: 1468

Javascript alert() issue

I'm new in javascript and having a small issue with the alert() function. I have this piece of code :

document.getElementById('picture').src="scene"+curScene+".png";
if(curScene!=0)
    alert(text);

The issue is that the browser executes the alert function before changing the image.Why is that? Isn't the code executed in order? Why does it jumps over lines?

I found something on this on google, but when I apply it to my script, it does't work.

Thank you!

Upvotes: 0

Views: 228

Answers (2)

Tyler McGinnis
Tyler McGinnis

Reputation: 35286

var newImage = document.getElementById('picture').src="scene"+curScene+".png";
newImage.onload = function(){
  if(curScene != 0){
    alert('text');
  }
}

Upvotes: 1

Homan
Homan

Reputation: 26768

Javascript code is asyncronous. Statements that take a long time to load like ajax or image loading execute in parallel. If you really want to alert() after the image src is loaded then you should wrap that code in a callback such as onload event.

Upvotes: 0

Related Questions