testkhan
testkhan

Reputation: 1787

setInterval is not working

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?

Upvotes: -1

Views: 1260

Answers (3)

NilColor
NilColor

Reputation: 3532

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

Upvotes: 0

Mads Mobæk
Mads Mobæk

Reputation: 35940

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

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532445

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

Upvotes: 7

Related Questions