Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a JavaScript function after x seconds

Tags:

javascript

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>
like image 428
Haren Sarma Avatar asked Sep 14 '14 15:09

Haren Sarma


Video Answer


2 Answers

<script>
    window.onload = function(){
        //time is set in milliseconds
        setTimeout(div_show, 10000)
    };
</script>
like image 98
styke Avatar answered Sep 29 '22 05:09

styke


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.

like image 32
Quentin Avatar answered Sep 29 '22 06:09

Quentin