How to run JavaScript function in x seconds
I am trying to execute a JavaScript function after 10 seconds of loading the body. But it manifests itself immediately after the load on the body. I'm not a JavaScript expert, so I can't seem to find where the problem is. my code is below:
<script type="text/javascript">
window.onload=setInterval(div_show(), 10);
</script>
source to share
You need:
- Assign a function
onload
.setInterval
returns an interval id, not a function - Pass a function
setInterval
,div_show()
call a functiondiv_show
and pass its return value - Several of your seconds per 1000.The
setInterval
second argument takes a few milliseconds, not seconds.
Such:
onload = function () {
setInterval(div_show, 10 * 1000);
}
Finally, if you want the function to run 10 seconds after the document has loaded, rather than every 10 seconds since the document has loaded, use setTimeout
instead setInterval
.
source to share
Wrap it inside a function.
<script type="text/javascript">
window.onload = function(){
setInterval(div_show, 10);
}
</script>
Also, if you are sure you only want to execute this function once
when the body is loaded, you can also use setTimeout
instead setInterval
. how
<script type="text/javascript">
window.onload = function(){
setTimeout(div_show, 10);
}
</script>
If you want it to execute after 10 seconds, you need to set the timer parameter to number of seconds * 1000
In your case10*1000
Or
setTimeout(div_show, 10*1000);
or
setTimeout(div_show, 10000);
source to share