【问题标题】:Why does setInterval not work? I want a function to repeat every 500ms and so I tried to use setInterval but it doesn't work [duplicate]为什么 setInterval 不起作用?我想要一个函数每 500 毫秒重复一次,所以我尝试使用 setInterval 但它不起作用 [重复]
【发布时间】:2021-06-07 20:45:58
【问题描述】:
var direction;
function movement(){
    switch(direction){
        case 1: positionX = positionX + 10;
                break;
        case 2: positionX = positionX - 10;
                break;
        case 3: positionY = positionY - 10;
                break;
        case 4: positionY = positionY + 10;
                break;
    }
    snake.style.marginLeft = positionX + "px";
    snake.style.marginTop = positionY + "px";
}

function changeDirection(a){
    direction = a;
}

setInterval(movement(), 500);

我不知道为什么 setInterval 不起作用。 我尝试只写“funcName”、funcName、funcName() 并将函数放在 var 中,但它不起作用。

【问题讨论】:

    标签: javascript setinterval


    【解决方案1】:

    setInterval 接收回调作为第一个参数,但您尝试使用函数结果调用它。
    替换这个:

    setInterval(movement(), 500);
    

    用这个:

    setInterval(movement, 500);
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2022-01-05
    • 2021-06-07
    • 2018-05-08
    • 2020-07-04
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2020-03-19
    • 2020-08-29
    相关资源
    最近更新 更多