DEV Community

JennyJudova (they/them)
JennyJudova (they/them)

Posted on

SetInterval and EmberJs

Screenshot of Snake game

Context

I was working on rewriting a vanilla JS snake game in Ember JS. One of the basic features of the game is that the snake moves continuously even if the user is not pushing any button.

In vanilla JS the solution to this is straightforward
interval = setInterval(gameMoves, 1000)
and at the end of the game you just do
clearInterval(interval)`

My assumption was that Ember would not be much different, and would look like this:
this.interval =setInterval(this.gameMoves, 1000);
This did nothing.

Assuming the syntax was off somewhere (I am dyslexic so commas and brackets are my mortal enemies), I tried this:
this.interval = setInterval(this.gameMoves(), 1000);
this.gameMoves() ran once and stopped.

Problem

Digging in I discovered that when I console.log this' in this.moveOutcomes after running this.interval =setInterval(this.moveOutcomes, 1000); I don't actually get this but window`.

Screenshot of what happens when this is console logged in a function that was called by setInterval

After an evening of googling, asking twitter, assuming that I am losing my sanity, and reminding myself that if I can write something in vanilla JS then it surely can be done in Ember. My colleague had the answer to my conundrum this needed binding.

Solution

this.interval = setInterval(this.moveOutcomes.bind(this), 1000);

Alternative solution

Someone on twitter suggested to use later which worked quite well but I felt it was a bit of an overkill.

Here is a twiddle if you are interested.

Why am I sharing this?

Because Ember is awesome, and Ember newbies should be able to google for answers.

But if googling fails Ember Discord channel is amazing.

Top comments (0)