Reputation: 281
Helllo, I have a function that needs to be executed every 10 seconds. It works like this:
setInterval(function () {
}, 10000);
The problem is that I need this function to be executed once on page load - now the first execution happens only after 10 seconds. Is it possible to do what I want with setInterval, or is there another function?
Thank you for your time!
Upvotes: 2
Views: 9746
Reputation: 173662
This is the most obvious way:
var myFunction = function() {
};
myFunction();
setInterval(myFunction, 10000);
Alternatively, use setTimeout()
:
(function foo() {
// do stuff here
setTimeout(foo, 10000);
})();
Upvotes: 5
Reputation: 40106
There may be a better way, but this will work:
$(document).ready(function() {
var readyNow = 0;
//Runs immediately, waiting ten secs before setting flag to true
setTimeout(function(){
readyNow++;
},10000);
//Starts immediately, but flag won't be true for first ten seconds
setInterval(function () {
if (readyNow==1) {
//do your code
}
}, 10000);
}); //END document.ready()
Upvotes: 2
Reputation: 10713
You need to name the function which you want to execute like:
function myFunction() {
}
setInterval(myFunction, 10000);
Here is myFunction the function that is executed every 10 seconds. The call on the last line
Upvotes: 1
Reputation: 5840
Try this:
<script type="text/javascript">
var fnc=function(){
/* do your stuff here */
setTimeout(fnc, 1000);
};
$(document).ready(function(){
fnc();
});
</script>
Upvotes: 1