Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中如何在循环中添加延迟_Javascript_Loops_Time_Delay - Fatal编程技术网

在JavaScript中如何在循环中添加延迟

在JavaScript中如何在循环中添加延迟,javascript,loops,time,delay,Javascript,Loops,Time,Delay,在JavaScript中,如何向JavaScript循环添加延迟 在下面的代码中 snakeclass.prototype.start = function() { while(1){ if(this.collision()){ console.log("game over"); break; } this.movesnake(); // delay here by 300

在JavaScript中,如何向JavaScript循环添加延迟 在下面的代码中

snakeclass.prototype.start = function() {
    while(1){
        if(this.collision()){
            console.log("game over");
            break;
        }

        this.movesnake();

        // delay here by 300 miliseconds
    }
};

如何在这里使用设置超时功能

那不行。如果您执行以下操作,您的浏览器将冻结:

while (1) {}
但是,您可以使用setInterval

snakeclass.prototype.start = function() {
    var interval;
    var doo = function () {
        if(this.collision()){
            console.log("game over");
            clearInterval(interval);
        }
        this.movesnake();
    }.bind(this); // bind this so it can be accessed again inside the function
    doo();
    timeout = setInterval(doo, 300);
};

你的意思是,延迟整个while循环?可能重复的Hmm,尝试刷新页面。