1

I am new to programming and coding and I need help with a small project. I need to set a small time delay before a function gets activated. I am using an HTML5 canvas and trying to re-create pong. Anyway, would like to put a small time delay before the ballReset() function gets called. Also, that is not the entire script it is just the part where the ballReset() function gets called.

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;
    }
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
L.Polly
  • 11
  • 2
  • 2
    Are you looking for `setTimeout`? You can use it like: `setTimeout(function() { alert("It's been 500 ms") }, 500);` – Downgoat Jun 02 '17 at 17:55
  • https://www.w3schools.com/js/js_timing.asp – Ricky Mutschlechner Jun 02 '17 at 17:55
  • the answers below miss to explain that, while `ballReset` call will be delayed with `setTimeout`, the rest of the code in `moveEverything` will continue to execute without waiting for `ballReset` to get called. You need to explain why you want this delay and how it falls into the rest of your code logic. – Igor Jun 02 '17 at 18:12
  • New to code is different than new to SO or Internet. – manikant gautam Jun 03 '17 at 02:48

2 Answers2

1

There are two (mostly used) types of timer function in javascript setTimeout and setInterval (other)

Both these methods have same signature. They take a call back function and delay time as parameter.

setTimeout executes only once after the delay whereas setInterval keeps on calling the callback function after every delay secs.

both these methods returns an integer identifier that can be used to clear them before the timer expires.

clearTimeout and clearInterval both these methods take an integer identifier returned from above functions setTimeout and setInterval

Example:

setTimeout

alert("before setTimeout");

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

  alert("after setTimeout");

If you run the the above code you will see that it alerts before setTimeout and then after setTimeout finally it alerts I am setTimeout after 1sec (1000ms)

What you can notice from the example is that the setTimeout(...) is asynchronous which means it doesn't wait for the timer to get elapsed before going to next statement i.e alert("after setTimeout");

Example:

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);

If you run the the above code you will see that it alerts before setInterval and then after setInterval finally it alerts I am setInterval 5 times after 1sec (1000ms) because the setTimeout clear the timer after 5 seconds or else every 1 second you will get alert I am setInterval Infinitely.

How browser internally does that?

I will explain in brief.

To understand that you have to know about event queue in javascript. There is a event queue implemented in browser. Whenever an event get triggered in js, all of these events (like click etc.. ) are added to this queue. When your browser has nothing to execute it takes an event from queue and executes them one by one.

Now, when you call setTimeout or setInterval you callback get registered to an timer in browser and it gets added to the event queue after the given time expires and eventually javascript takes the event from the queue and executes it.

This happens so, because javascript engine are single threaded and they can execute only one thing at a time. So, they cannot execute other javascript and keep track of your timer. That is why these timers are registered with browser (browser are not single threaded) and it can keep track of timer and add an event in the queue after the timer expires.

same happens for setInterval only in this case the event is added to the queue again and again after the specified interval until it gets cleared or browser page refreshed.

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.

Hence, your callback may sometime take more than the specified delay time to be called specially when your other code blocks the thread and not giving it time to process what's there in the queue.

And as I mentioned javascript is single thread. So, if you block the thread for long.

Like this code

while(true) { //infinite loop 
}

Your user may get a message saying page not responding.

Nadir Laskar
  • 4,012
  • 2
  • 16
  • 33
0

What you are looking for is the setTimeout fn, and pass the fn ballReset() as a callback!

For example, delayed by 3000ms,

setTimeout(function () {
  ballReset()
}.bind(this), 3000)

You can find more about setTimeout in the following documentation page https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

punkbit
  • 7,347
  • 10
  • 55
  • 89
  • As OP stated, they are new to coding, I think it's worth mentioning that `setTimeout` is asynchronous and will not hold up execution – Patrick Barr Jun 02 '17 at 17:57
  • 3
    what is the point of anonymous function being bound to `this` and not using it inside? – Igor Jun 02 '17 at 18:03
  • If you don't have any arguments to ballReset, you can just do setTimeout(ballReset, 3000); – Peter LaBanca Jun 02 '17 at 18:30
  • @PeterLaBanca `ballReset` may need the calling context, but not the way shown in this answer. As for parameters, `setTimeout` allows to specify them as additional arguments. – Igor Jun 02 '17 at 18:31