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 p开发者_JS百科age it works for me. How can I fix that?
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);
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);
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);
精彩评论