tags:

views:

117

answers:

4

Suppose I have a function:

function chk(){
   alert("Welcome");
}

window.onload = chk();
setInterval("chk();", 5000);

but it is not working but when I refresh the page it works for me. How can I fix that?

+6  A: 

This works just fine for me. Note the use of the function reference instead of calling the function and assigning the return value. SetInterval need not use a string -- which forces an eval of the argument. You can also use a function reference (or an anonymous function) as the argument.

function chk() {
    alert('checking');
}

window.onload = chk;

setInterval(chk,5000);
tvanfosson
Yes, the function reference method of calling is preferred.
Nosredna
OP - Notice the lack of a parameter list on the function reference.window.onload = chk(); would run the function, and set window.onload to whatever value is returned from the function.
Adam A
+1  A: 

If you want the alert to display once, after 5 seconds, use:

function chk(){
   alert("Welcome");
}

setTimeout("chk()", 5000);

If you want the alert to appear every 5 seconds (extremely annoying, but there is other legitimate for setInterval)

function chk(){
   alert("Welcome");
}

setInterval("chk()", 5000);
Mads Mobæk
A: 

Where in your page is this javascript? Do you have it in the head?

Justin C
A: 
function chk(){
   alert("Welcome");
}

window.onload = chk();
setInterval("chk();", 5000);

window.onload becomes undefined here -- chk doesn't return anything. And you need to rewrite your setInterval like this: setInterval(chk, 5000);

NilColor
Are you able to read the other answers?
Crescent Fresh
Yes.Thanks to point me.
NilColor