8

I am trying a JavaScript function after 10 second of body load. But it is showing immediatly after body load. I am not expert in JavaScript, so I am not able to find where is the problem. my code is below:

<script type="text/javascript">
window.onload=setInterval(div_show(), 10);
</script>
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Haren Sarma
  • 173
  • 1
  • 1
  • 9

4 Answers4

7

You need to:

  1. Assign a function to onload. setInterval returns an interval id, not a function
  2. Pass a function to setInterval, div_show() will call the div_show function and pass its return value
  3. Multiple your number of seconds by 1000. setInterval's second argument is accepts a number of milliseconds not seconds.

Such:

onload = function () {
    setInterval(div_show, 10 * 1000);
}

Finally, if you want to run the function 10 seconds after the document loads, rather than every 10 seconds starting from when the document loads, use setTimeout instead of setInterval.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
7
<script>
    window.onload = function(){
        //time is set in milliseconds
        setTimeout(div_show, 10000)
    };
</script>
styke
  • 2,116
  • 2
  • 23
  • 51
3

Wrap it inside a function.

<script type="text/javascript">
window.onload = function(){
    setInterval(div_show, 10);
}
</script>

Also, if you're sure if you want to execute this function only once when the body loads, you might as well want to use setTimeout instead of setInterval. Like

<script type="text/javascript">
window.onload = function(){
    setTimeout(div_show, 10);
}
</script>

If you want 10 it to execute after 10 seconds, you need to set the timer parameter to number of seconds * 1000 In your case, 10*1000

Either

setTimeout(div_show, 10*1000);

or

setTimeout(div_show, 10000);
AdityaParab
  • 7,024
  • 3
  • 27
  • 40
3

This code will work. Just set your time in milliseconds and write your JS code on loadAfterTime function:

<script>
 window.onload = function(){

        setTimeout(loadAfterTime, 1000)
};


function loadAfterTime() { 
// code you need to execute goes here. 
}
</script>
Jakir Hossain
  • 800
  • 6
  • 12