最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript - SetInterval doesn't function properly - Stack Overflow

programmeradmin0浏览0评论

I got this piece of script (runned locally):

<script>

last = 0;

function uploadnew(){

var randomnumber=Math.floor(Math.random()*6);
if(randomnumber != last){
    document.forms['f'+randomnumber].submit();
} else { uploadnew(); }

}

setInterval (uploadnew(), 1000*60*5);

</script>

But it seems that setInterval is not working / send form function doesn't work...

Any help will be appreciated!

Thanks!

I got this piece of script (runned locally):

<script>

last = 0;

function uploadnew(){

var randomnumber=Math.floor(Math.random()*6);
if(randomnumber != last){
    document.forms['f'+randomnumber].submit();
} else { uploadnew(); }

}

setInterval (uploadnew(), 1000*60*5);

</script>

But it seems that setInterval is not working / send form function doesn't work...

Any help will be appreciated!

Thanks!

Share Improve this question edited Oct 31, 2010 at 17:25 Brad Mace 27.9k17 gold badges109 silver badges152 bronze badges asked Oct 31, 2010 at 17:23 PaulPaul 1,9668 gold badges25 silver badges32 bronze badges 2
  • If you submit a form to the same window, it will load a new page and stop the interval – mplungjan Commented Oct 31, 2010 at 17:25
  • yeap, I know. I'm loading it into iframe. – Paul Commented Oct 31, 2010 at 17:31
Add a comment  | 

4 Answers 4

Reset to default 10

You need to call setInterval() without parenthesis on your function, like this:

setInterval(uploadnew, 1000*60*5);

Using parenthesis you're calling it immediately and assigning the result (undefined) to be run on an interval, instead don't use parenthesis to pass the function itself, not the result of the function.

You need to remove the () after uploadnew within the setInterval call:

setInterval (uploadnew, 1000*60*5);

In JavaScript, functions are first-class objects which can be passed to other functions. In this example, you want to pass the function itself to setInterval, not call it first and then pass its return value.

Using setInterval ("uploadnew()", 1000*60*5); is not recommended because it is a "hidden" form of eval. Eval is evil and you shouldn't use it if you don't have to.

You need to pass a reference to the function instead of calling it.

This:

setInterval (uploadnew(), 1000*60*5);

should be:

setInterval (uploadnew, 1000*60*5);

If you were to call it as you were, you would need to have uploadnew() return a function to be passed to setInterval.

function uploadnew() {
    return function(){
        var randomnumber=Math.floor(Math.random()*6);
        if(randomnumber != last) {
            document.forms['f'+randomnumber].submit();
        } else { uploadnew()(); }
    }
}

Note the change to the recursive call.

Use

setTimeout ( expression, timeout );
发布评论

评论列表(0)

  1. 暂无评论