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>
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 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.
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”.
You're looking for setTimeout()
, which does exactly that.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With