0

I'm developing a game, and I'm having some trouble. I would like to have a funtion wait(frames) that would make a function wait some frames before continuing.

I have a main loop like this:

setInterval(function() {
    refreshMap();
}, 35 );

And a function like that:

function sayHello(){
    console.log("hello 1");
    wait(5);
    console.log("hello 2");
}

The wait(5) function would make the game refresh 5 times before executing console.log("hello 2");. Is it possible to do without freezing the entire game like setTimeout()?

Vins
  • 1
  • 2
  • The problem with js is that whatever you do in your code javascript can execute code only in a single thread. Consider of using something like java-applet or .Net SignalR – Fabjan Jul 02 '15 at 19:42
  • 2
    _“Is it possible to do without freezing the entire game like `setTimeout()`?”_ – unclear what you mean by that; in fact, using a timeout is one of the ways to _not_ “freeze” anything. – CBroe Jul 02 '15 at 19:45

1 Answers1

0

I don't see how your first and second function interact. But something like this would make the game wait for 10 seconds without freezing the game:

setInterval(refreshMap,35);
sayHello();

function sayHello(timeToContinue) 
{
    if (!timeToContinue) //the first time it's called
    {
        console.log("hello 1");
        var nextTime = new Date();
        nextTime.setSeconds(nextTime.getSeconds() + 10);
        window.setTimeout(function(){sayHello(nextTime);}), 1); //call this function again
        return;
    }
    if (new Date() < timeToContinue) //when next the function gets here check 10 seconds have passed
    {
        window.setTimeout(function(){sayHello(timeToContinue);}), 1); //else come back later
        return;
    }
    console.log("hello 2");
}
Richard
  • 14,798
  • 21
  • 70
  • 103