我想用var

时间:2018-01-28 10:26:21

标签: javascript

我正在制作一个蛇游戏但是出现了一些问题。

几乎所有东西都工作正常,但问题是当另一个正在执行时我必须停止一个setInterval。我认为我应该使用clearInterval

我希望当我按右箭头键时红色矩形开始移动,但是要将setInterval用作var,这样我就可以用var替换clearInterval }。

我该怎么办?

<html>
<body>
    <canvas id="gamecanvas" width="1330" height="625"></canvas>
    <script>
        var canvas;
        var canvasContext;

        window.onload = function () {
            canvas = document.getElementById("gamecanvas");
            canvasContext = canvas.getContext("2d");
        }

        function both() {
            moveSnake();
            drawEvery();
        };

        function moveSnake() {
            snakeX = snakeX + snakeSpeedX;

            if (snakeX + 10 >= 500 + 400) {
                snakeX = 450;
            }
        }

        window.addEventListener('keydown', this.changedir, false);


        function changedir(event) {
            var code = event.keyCode;
            //right arrow key
            if (code == 39) {
                //this set interval needs to be replaced by a var.
                setInterval(both, 1000 / 30)
            };
        }

        function drawEvery() {
            canvasContext.fillStyle = "yellow";
            canvasContext.fillRect(0, 0, canvas.width, canvas.height);

            canvasContext.fillStyle = "black";
            canvasContext.fillRect(canvasX, canvasY, 500, 500);

            canvasContext.fillStyle = "red";
            canvasContext.fillRect(snakeX, snakeY, 20, 20);

            canvasContext.fillStyle = "green";
            canvasContext.fillRect(500, 200, 20, 20);

        }
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

setInterval会返回intervalId,您可以使用该 //this set interval needs to be replaced by a var. var interval = setInterval(both, 1000/30); 清除时间间隔

clearInterval(interval)

以后你可以使用

let UserAPI = {

    login(username, password){
        const requestOptions = {
            method: 'POST',
            headers: {'Authorization': 'Basic ' + btoa('livechat-api-client:livechat'), 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
            body: `username=${username}&password=${password}&grant_type=password`
        };
        return fetch('http://localhost/cronos/oauth/token', requestOptions)
            .then(response => {
                if (!response.ok) {
                    return Promise.reject(response.statusText);
                }
                return response.json();
            })
            .then(user => {
                // login successful if there's a jwt token in the response
                if (user && user["access_token"]) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('user', JSON.stringify(user));
                }
                return user;
            });
    }
}

export default UserAPI;

这里要注意的一点是,必须在使用clearInterval的同一范围内声明变量