Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Run setInterval only once [duplicate]

Possible Duplicate:
setInterval - How to fire only once?

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>
like image 723
Homie Avatar asked Jan 24 '13 17:01

Homie


People also ask

Does setInterval repeat?

Yes, setInterval repeats until you call clearInterval with the interval to stop. By way of example, the following code will count to 5. setInterval sets up the counter, setTimeout sets up a single event in 5 seconds to stop the counter, and clearInterval stop counting.

Why is setInterval not accurate?

Why are setTimeout and setInterval not accurate? To answer this question, you need to understand that there is a mechanism called event loop in the JavaScript host environment (browser or Node. js). It is necessary for front-end developers to understand this mechanism.

What can I use instead of setInterval?

Nested setTimeout calls are a more flexible alternative to setInterval , allowing us to set the time between executions more precisely. Zero delay scheduling with setTimeout(func, 0) (the same as setTimeout(func) ) is used to schedule the call “as soon as possible, but after the current script is complete”.


2 Answers

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

like image 76
SLaks Avatar answered Sep 18 '22 08:09

SLaks


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.

like image 28
Jani Hyytiäinen Avatar answered Sep 22 '22 08:09

Jani Hyytiäinen