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>
4
  • onload should have a function that can be executed, try: window.onload=function(){ setInterval(div_show(), 10); }; Commented Sep 14, 2014 at 15:28
  • 2
    1) use setTimeout, 2) use a function Commented Sep 14, 2014 at 15:29
  • 1
    @LearningNeverStops Your code will not work unless you remove the () Commented Sep 14, 2014 at 15:33
  • @mplungjan haa :) correct, my mistake :| it has to be without () --- window.onload=function(){ setInterval(div_show, 10); }; Commented Sep 14, 2014 at 16:26

4 Answers 4

7
<script>
    window.onload = function(){
        //time is set in milliseconds
        setTimeout(div_show, 10000)
    };
</script>
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.