Haren Sarma
Haren Sarma

Reputation: 171

How to run a JavaScript function after x seconds

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>

Upvotes: 8

Views: 13680

Answers (4)

Jakir Hossain
Jakir Hossain

Reputation: 1072

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>

Upvotes: 3

AdityaParab
AdityaParab

Reputation: 7100

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);

Upvotes: 3

styke
styke

Reputation: 2174

<script>
    window.onload = function(){
        //time is set in milliseconds
        setTimeout(div_show, 10000)
    };
</script>

Upvotes: 7

Quentin
Quentin

Reputation: 943108

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.

Upvotes: 7

Related Questions