JavaScript - SetInterval doesn't function properly

前端 未结 4 1748
忘掉有多难
忘掉有多难 2021-01-13 22:40

I got this piece of script (runned locally):



        
相关标签:
4条回答
  • 2021-01-13 22:50

    Use

    setTimeout ( expression, timeout );
    
    0 讨论(0)
  • 2021-01-13 22:52

    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.

    0 讨论(0)
  • 2021-01-13 22:53

    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.

    0 讨论(0)
  • 2021-01-13 23:05

    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.

    0 讨论(0)
提交回复
热议问题