16

I would like to run the following code only once, so after 2 seconds it will change the iframe's src, but won't try to do it again and again.

<script type="text/javascript">
    setInterval(function () {document.getElementById('iframe').src = "http://www.y.com";}, 2000);
    </script>
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Homie
  • 437
  • 4
  • 11
  • 23

3 Answers3

41

You're looking for setTimeout(), which does exactly that.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
16

yep...

window.setTimeout(function(){
        // code to run after 5 seconds...
}, 5000);

or by taking your method to outer context

function myMethod(){
    // code to run after 5 seconds...
};

window.setTimeout(myMethod, 5000);

The latter is useful if you have a method you don't plan to execute ONLY wit that timeout.

Jani Hyytiäinen
  • 5,293
  • 36
  • 45
  • 2nd method yet not correct, it runs immediately, and again after 5 seconds, if `myMethod` would return a reference to a function :-(. – Teemu Jan 24 '13 at 18:58
  • Hmm... only you'd needed to do is to remove parenthesis from the `myMethod()` --> `window.setTimeout(myMethod, 5000);`, though this is a good form when you need to pass arguments to `myMethod()`. – Teemu Jan 24 '13 at 19:16
3

Use setTimeout, you can see more details in Mozilla site.

Erick Ribeiro
  • 756
  • 2
  • 8
  • 14