Justin Colyar
Justin Colyar

Reputation: 11

can't get setInterval to work in given context

I have tried countless different approaches to this, and spent far too many hours trying to solve something that is probably overly simple. For some reason, I am unable to get the following setInterval call to work. It does call once, but DOES NOT call every 1000 milliseconds. It would be helpful for some input as to why this the alert is not being called every 1 second (1000 milliseconds)

<html>
<head>
<script>
function user(h){
this.userHunger = h;
this.userAction='Move';

this.start=function(){
    this.hungerClockStart();
};
this.hungerClockStart=function(){
    //setInterval(this.updateHungerScreen(),1000);
    this.hungerClock = (setInterval(alert(1),1000));
};

};
var user1=new user(100);
function displayUserHunger(u){
u.start();
}
</script>
</head>
<body>
<h1>Display a User's Hunger:<br></h1>
<div>
<h2 id = 'HungerBarVisual'> </h2>
<button onclick="user1.start()">Start</button>

</div>
</body>
</html>

Upvotes: 1

Views: 106

Answers (2)

Halcyon
Halcyon

Reputation: 57721

Something like:

setInterval(this.updateHungerScreen(),1000);

Indicates that you're probably using setInterval wrong.

What is happening here is that the return value of this.updateHungerScreen() will get called as a function. So you probably want this instead:

setInterval(this.updateHungerScreen,1000);

this.updateHungerScreen (no brackets!) is the function you want to call.


Similarly setInterval(alert(1),1000) is equivalent to alert(1);setInterval(null,1000)

You probably want:

setInterval(function () {
    alert(1); // will get called every 1000ms
},1000);

Upvotes: 1

elclanrs
elclanrs

Reputation: 94141

setInterval takes a function object:

this.hungerClock = setInterval(func, 1000);

If you want to pass parameters you need to use an extra anonymous function:

this.hungerClock = setInterval(function(){ alert(1) }, 1000);

Upvotes: 0

Related Questions