Srikanth Srikanth - 26 days ago 7
Javascript Question

Image source change with jquery not completing until event completes

I need to change the image source

onClick
, for that i created the jquery click and the image source is not effecting until the click completes

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.bg {
background-image: url("paper.gif");
background-color: #cccccc;
}
</style>

<script>
$(document).ready(function(){
$("a").click(function(){
//alert($("#img").attr("src"));
$("#img").attr("src","https://www.w3schools.com/images/driveicon.png");
//alert($("#img").attr("src"));
$("h1").attr("class","");
//alert('hi');
sleep(10000000);
//alert('hi1');
});
});
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
</script>
</head>
<body>
<h1 class="bg">Hello World!</h1>
<a>
<img id="img" src="https://tpc.googlesyndication.com/daca_images/simgad/16193915113295470335?w=195&h=102"/>
</a>
<br>
<p id="img1"/>
</body>
</html>


In the above code, image src changing after few seconds of the click.

I need to change the image source immediately after click.

Thanks in advance

Answer Source

Your problem is because Javascript is single-threaded. Hence while the massive loop in your sleep() function is running nothing else can happen. In turn, this means that the DOM does not get time to render the change you made to the src of the img element, and it only appears to occur once the loop terminates.

The way to solve this is to make use of one of the timer functions which JS provides. In your case setTimeout() would be the most appropriate:

$(document).ready(function() {
  $("a").click(function() {
    $("#img").attr("src", "https://www.w3schools.com/images/driveicon.png");
    $("h1").attr("class", "");
    setTimeout(doSomethingElse, 1000);
  });
});

function doSomethingElse() {
  console.log('Doing something else here...');
}
.bg {
  background-image: url("paper.gif");
  background-color: #cccccc;
}

#img {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="bg">Hello World!</h1>
<a>
  <img id="img" src="http://i.imgur.com/HazyBBo.jpg" />
</a><br />
<p id="img1" />