jimbo123
jimbo123

Reputation: 287

Javascript function stored in variable error

Is there any reason why I would be getting the error

Uncaught TypeError: inter is not a function at movingPiece (script.js:270) at keyboardMove (script.js:146)

in this code:

var inter = setInterval(function() {
  draw();
  b_ctx.globalCompositeOperation = "copy";
  b_ctx.fillStyle = "purple";
  b_ctx.beginPath();
  b_ctx.arc(xcoord, y, 45, 0, Math.PI * 2, true);
  b_ctx.fill();
  y += 1;
  if (y > endY) clearInterval(inter)
}, 25);

inter();

Upvotes: 0

Views: 46

Answers (3)

warch
warch

Reputation: 2609

Try this:

var inter = function(){
  var x= setInterval(function(){
                draw();
                b_ctx.globalCompositeOperation="copy";
                b_ctx.fillStyle = "purple";
                b_ctx.beginPath();
                b_ctx.arc(xcoord, y, 45, 0, Math.PI*2, true);
                b_ctx.fill();
                y+=1;
                if(y>endY) clearInterval(x)}, 25);
}
inter();

Upvotes: 0

mrinalmech
mrinalmech

Reputation: 2175

setInterval does not return a function. Modify it like this.

   var inter = function(){
                    var interVar = setInterval(function(){
                    draw();
                    b_ctx.globalCompositeOperation="copy";
                    b_ctx.fillStyle = "purple";
                    b_ctx.beginPath();
                    b_ctx.arc(xcoord, y, 45, 0, Math.PI*2, true);
                    b_ctx.fill();
                    y+=1;
                    if(y>endY) clearInterval(interVar)}, 25);
               }

Then you can run inter() and have it run setInterval

Upvotes: 0

user8003769
user8003769

Reputation:

inter is not really a function. So you can't call it. It is called automatically every 25 millisecond.

You are getting the error because you are calling it. It is automatically called. You don't need to call it or invoke it.

Upvotes: 1

Related Questions