Search code examples
javascripthtmlcsstimerdelay

Delay function after calling in Javascript


I've been having trouble finding any delays right after a function is executed. The problem is that the href loads a little slow and the function takes in effect before the _target page is loaded. You can see the change coming into effect immediately. I'd like to have a little timer to wait a few seconds before the function takes affect.

I've tried setInterval inside a var, but it doesn't seem to be working. setInterval by itself keeps running once the page is clicked and I don't want that. I want the timer to be started once the image is clicked and the link loaded.

<script type='text/javascript'>

function change() {
  var image = document.getElementById('doge');
  image.src = 'img/doge.png';
  document.getElementById("text").innerHTML="<b>such wow</b> much amaze <b><i>very effort</b></i>"  
}

</script>

<a href='img/doge.jpg' target="_blank"><img src='Logo_256.png' alt='doge' id='doge' onclick='change();'></a>
<small id='text'>This page was last modified on Wednesday, November 20, 2013 8:43:13 PM</small>

I assure you everything works, so don't mind if the .jpg or .png match up (just edited right now).


Solution

  • Add a timeout to the things that the function does, so the delay occurs when the function runs what you want to happen in your change() function after a setTimeout():

    var change = function(){
      setTimeout(function() { 
        var image = document.getElementById('doge');
        image.src = 'img/doge.png';
        document.getElementById("text").innerHTML="<b>such wow</b> much amaze <b><i>very effort</b></i>"  
      }, 5000);
    };