javascript - 如何在 JavaScript 中为函数添加时间延迟?

标签 javascript html

我是编程和编码新手,我需要一个小项目的帮助。我需要在激活功能之前设置一个小的时间延迟。我正在使用 HTML5 Canvas 并尝试重新创建 pong。无论如何,想在 ballReset() 之前稍微延迟一下函数被调用。另外,这不是整个脚本,它只是 ballReset() 的部分。函数被调用。

function moveEverything() {
    computerMovement();

    ballX = ballX + ballSpeedX;
    ballY = ballY + ballSpeedY;

    if(ballX < 0) {
        if(ballY > paddle1Y &&
            ballY < paddle1Y+PADDLE_HEIGHT) {
            ballSpeedX = -ballSpeedX;
        } else {
            ballReset();
            player2Score++;
        }
    }

    if(ballX > canvas.width) {
        if(ballY > paddle2Y &&
            ballY < paddle2Y+PADDLE_HEIGHT) {
            ballSpeedX = -ballSpeedX;
        } else {
            ballReset();    
            player1Score++;
        }
    }
    if(ballY < 0) {
        ballSpeedY = -ballSpeedY;
    }
    if(ballY > canvas.height) {
        ballSpeedY = -ballSpeedY;
    }
}

最佳答案

JavaScript 中有两种(最常用的)定时器函数 setTimeoutsetInterval ( other )

这两个方法具有相同的签名。它们采用回调函数和延迟时间作为参数。

setTimeout 仅在延迟后执行一次,而 setInterval 在每个延迟秒后继续调用回调函数。

这两个方法都会返回一个整数标识符,可用于在计时器到期之前清除它们。

clearTimeoutclearInterval 这两个方法都采用从上述函数 setTimeoutsetInterval 返回的整数标识符p>

示例:

<强> setTimeout

alert("before setTimeout");

setTimeout(function(){
        alert("I am setTimeout");
   },1000); //delay is in milliseconds 

  alert("after setTimeout");

如果您运行上述代码,您将看到它在setTimeout之前发出警报,然后在setTimeout之后发出警报最后它在 1 秒(1000 毫秒)后提醒 I am setTimeout

从示例中您可以注意到,setTimeout(...) 是异步的,这意味着它不会等待计时器结束后才转到下一条语句,即 Alert("setTimeout 后");

示例:

<强> setInterval

alert("before setInterval"); //called first

 var tid = setInterval(function(){
        //called 5 times each time after one second  
      //before getting cleared by below timeout. 
        alert("I am setInterval");
   },1000); //delay is in milliseconds 

  alert("after setInterval"); //called second

setTimeout(function(){
     clearInterval(tid); //clear above interval after 5 seconds
},5000);

如果您运行上述代码,您将看到它在 setInterval 之前发出警报,然后在 setInterval 之后发出警报最后它会在 1 秒(1000 毫秒)后提醒 I am setInterval 5 次,因为 setTimeout 在 5 秒后清除计时器,否则每 1 秒你就会收到提醒 我设置Interval无限。

浏览器内部是如何做到这一点的?

我会简单解释一下。

要理解你必须了解 JavaScript 中的事件队列。浏览器中实现了一个事件队列。每当 js 中触发事件时,所有这些事件(如单击等)都会添加到此队列中。当您的浏览器没有要执行的内容时,它会从队列中获取一个事件并一一执行它们。

现在,当您调用 setTimeoutsetInterval 时,您的回调将注册到浏览器中的计时器,并在给定时间到期后添加到事件队列,最终使用 javascript从队列中取出事件并执行它。

之所以会发生这种情况,是因为 javascript 引擎是单线程的,它们一次只能执行一件事。因此,他们无法执行其他 JavaScript 并跟踪您的计时器。这就是为什么这些计时器向浏览器注册(浏览器不是单线程的),并且它可以跟踪计时器并在计时器到期后在队列中添加事件。

只有在这种情况下,setInterval 才会发生同样的情况,事件会在指定的时间间隔后一次又一次地添加到队列中,直到它被清除或浏览器页面刷新。

Note

The delay parameter you pass to these functions is the minimum delay time to execute the callback. This is because after the timer expires the browser adds the event to the queue to be executed by the javascript engine but the execution of the callback depends upon your events position in the queue and as the engine is single threaded it will execute all the events in the queue one by one.

因此,您的回调有时可能需要超过指定的延迟时间来调用,特别是当您的其他代码阻塞线程并且没有给它时间来处理队列中的内容时。

正如我提到的,javascript 是单线程的。所以,如果你长时间阻塞线程。

喜欢这段代码

while(true) { //infinite loop 
}

您的用户可能会收到一条消息,提示页面未响应

关于javascript - 如何在 JavaScript 中为函数添加时间延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44334796/

相关文章:

javascript - Jquery 通过循环获取带 id 的整数值

javascript - 检测 Android Chrome HTML Webapp 的重新打开

php - 解析文档时是否可以检测 HTML 元素的位置(页脚、侧边栏)?

html - 可点击的 Div vs 按钮 vs href?

javascript - 在 JavaScript 方面需要帮助,openWindow();

Javascript Tic Tac Toe - 获胜功能不调用/工作

javascript - 如何从另一种颜色中减去一种颜色

javascript - Window.scrollTo 在 React 中未定义

javascript - 不使用 jQuery 重写随机/按钮 Javascript

javascript - jQuery 复制和粘贴使用 document.execCommand ("copy") 和 ("paste")