简体   繁体   中英

Passing dynamic variables to function using setInterval

I am trying to pass "dynamic" (data is changed frequently by keypress event) body and direction .

I am calling function to like this:

snakeGame.createInterval(snakeGame.move, grid, body, direction, interval);



  createInterval: function(f, grid, body, direction, interval) {
    setInterval(function() { f(grid, body, direction); }, interval);
  },

Problem is that both body and direction always keep same data when function was called.

Let's say that direction was 'right' when calling it first time and before second occurence happens, direction was changed to 'up' , but this function still reads it as old 'right' .

How do I make sure that passed parameters are always up-to-date?

(Let me know if you need further clarification)

To see changes to values, you need references to those values, and make sure that both the code that changes values and the code that read the values use a reference to the same value.

There are several ways to do this, but it will involve an object with several object properties which will have the targetted values. But you will pass the object, not the individual values.

From the little you have provided, it looks like you have a snakeGame object. You could use that object to store some of the properties, for instance, it could have a property grid . But you could also introduce another object, for storing things you'd rather not have in your snakeGame object. This could be the case for body and/or direction .

For instance:

// Use object properties instead of separate variables: 
var snake = {
    body: 'xxxx',
    direction: 'L'
}

var snakeGame = {
    // You can also add properties to your existing object:
    grid: [[0,0,0],[0,0,0],[0,0,0]],
    createInterval: function(f, snake, interval) {
        // Pass `this` and snake objects:
        setInterval(f.bind(this, snake), interval); 
    },
    move: function(snake) {
        // use this.grid, snake.body and snake.direction: 
        //....
    }
    // etc
};

// Call with objects only (except for the constant interval)
snakeGame.createInterval(snakeGame.move, snake, interval);

// When you change direction:
$('#up').keydown(function () {
    // ... do not assign to snake, but to snake.direction:
    snake.direction = 'U';
    // ...
    // Same principle with snake.body.
});

I just chose to define grid as a property of snakeGame , and direction and body as properties of a newly introduced object. But you may want to do it differently. This is just an example. The essence is that you pass along objects, not primitive values, but that you assign to properties of those objects, never redefining the objects themselves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM