[ACCEPTED]-How to delay calling of javascript function?-dom-events

Accepted answer
Score: 75

setTimeout is compatible with all browsers since 1996. You 7 should avoid the evaluation of "functionName()" and 6 instead do:


UPDATE: If you initially expect a variable 5 passed to the function and none when in 4 the timeout, you need to do this instead:

setTimeout(function() { functionName() },5000)

However 3 you are calling the onload incorrectly, so you 2 need to do either this:

window.addEventListener("load",function() {
  // your stuff

or the simpler

window.onload=function() {
  // your stuff

or, since 1 you are using jQuery, this:

$(document).ready(function() {
    // your stuff

or just this:

$(function() {
    // your stuff
Score: 5

If you want to be 100% sure that it's when 4 the page ACTUALLY loads, use:

   //After EVERYTHING loads, including images.

The other's 3 solution, onload works, but it loads once the 2 DOM is ready, but not when the window is 1 actually finished loading.

Score: 3

If you're going to be using jQuery then 2 it's preferable to attach an event to the 1 document ready event using one of the following:



$(document).ready(function () { /* do stuff */ });




$(function () { /* do stuff */ });
Score: 1

   //Code goes here


or old style

<body onload="myFunction()">


Score: 0

Would be best to use a framework like jQuery.
In 4 jQuery you can define a function like this:

$(document).ready(function() {


This 3 way it will be called when the DOM is fully 2 loaded.

A full documentation of the ready() function 1 can be found here.

More Related questions