Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - SetInterval doesn't function properly

Tags:

javascript

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!

like image 692
Paul Avatar asked Nov 30 '22 17:11

Paul


2 Answers

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.

like image 105
Nick Craver Avatar answered Dec 05 '22 07:12

Nick Craver


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.

like image 41
PleaseStand Avatar answered Dec 05 '22 06:12

PleaseStand