Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Javascript handle assigning setInterval() to a variable?

I have what seems like a basic javascript question that I can't wrap my head around. Why does the below code snippet work (taken from w3 schools)?

Essentially what I'm asking is why does the "myVar" variable below execute the setInterval method without an explicit call? My best guess is that is has to do with the way javascript handles variable assignment?

<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<p>After clicking away the alert box, an new alert box will appear in 3 seconds. This goes on forever...</p>

<button onclick="myFunction()">Try it</button>

<script>
var myVar;

function myFunction() {
    myVar = setInterval(alertFunc, 3000);
}

function alertFunc() {
  alert("Hello!");
}
</script>

</body>
</html>

In case any further clarification is needed, here is a code snippet from my current work:

var refresh = setInterval(function() {
      $("#div").load('Query.html');
   }, 1000);

So my question is, why does the above work without calling the "refresh" variable elsewhere?

like image 464
pmcy85 Avatar asked Oct 23 '25 23:10

pmcy85


1 Answers

setInterval() does the cyclic calls in itself(see edit) and returns the ID of the process handling the cyclic invokations. The purpose of assigning the return value is to use clearInterval() afterwards since it requires you to pass the return value of a setInterval() (= the process ID) as its parameter.

In your case, if you want the function you passed in setInterval() to not be called again (by the "cycling call chain" you created using setInterval) you can simply do clearInterval(refresh).

EDIT

setInterval needs two parameters : an inline function (or a function pointer) and an integer.

What setInterval does is wait {integer passed} milliseconds and then calls the function and redo the same thing over and over until you call clearInterval passing setInterval's return value.

like image 165
Vivick Avatar answered Oct 26 '25 13:10

Vivick