Shawn
Shawn

Reputation: 1183

JS: Your function is not a function! TypeError

I have a small RTS game where you can attack a monster. I want it setup that when the game loads or starts, the strike() function will trigger after 3 seconds. However when I run this code below, I get a type-error that "strike()" is not a function. If its not a function, what is it then?

If your wondering what player.cc means, it stands for current character. The rest is just referring to a balance meter I have in the game.

dom.el("strike").onclick = function strike() {
    HitCalc(player.cc, monster.cc);
    actor.expCounter(player.cc);
    actor.balanceCounter(player.cc, monster.cc);
};

 setTimeout(strike(), 3000);

Additional code that may help:

dom = {
    el: function (id){
        return document.getElementById(id);
    },

HTML:

<button id="strike" type="button" class="buttons">Strike</button>

Upvotes: 0

Views: 114

Answers (1)

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64943

While you think that a function with name assigned to an event handler is still hoisted and declared in your current scope, you're mistaken on this part: it's still a function assigned to a property like any anonymous, inline function.

What you need is this:

function strike() {
    HitCalc(player.cc, monster.cc);
    actor.expCounter(player.cc);
    actor.balanceCounter(player.cc, monster.cc);
};

dom.el("strike").onclick = strike;

// Note that setTimeout expects a reference to the function rather than
// a function call!!
setTimeout(strike, 3000);

Upvotes: 2

Related Questions