Reputation: 29
I need pause my script to allow a wait between events in my game. If anyone could explain how I could do this, in simple terms (because I am a newbie), I would really appreciate it. Thank you in advance!
Upvotes: 2
Views: 1226
Reputation: 13129
setTimeout is the way to go.
Usage example:
console.log('before')
setTimeout(function() {
console.log('after - 500ms later')
}, 500)
console.log('still before')
setTimeout won't pause javascript, there's no way to do that. Instead, it'll schedule a function to be called at some point in the future. This is why when you run the code snippet, you'll see "before" and "still before" get logged at the same time. Only the contents in the function passed into setTimeout() will happen after the delay provided.
Note that this means that there is no way to return a value from the setTimeout call for usage afterwards - this is something that many newcomers struggle with when they're first trying to work with async logic (like setTimeout). everything that you want to happen after this delay has to be put inside the setTimeout function (or, you can of course call other functions from it if you feel like your function is starting to get a little big).
Upvotes: 0
Reputation: 3652
Ideally you'd want a loop to control timing in your game for "pauses", which would just be iterations of the loop. Think of FPS in a game and how each cycle it will draw something new.
function update(progress) {
// Update the state of the world for the elapsed time since last render
}
function draw() {
// Draw the state of the world
}
function loop(timestamp) {
var progress = timestamp - lastRender
//you would call your functions here when the game is "running":
update(progress)
draw()
lastRender = timestamp
window.requestAnimationFrame(loop)
}
var lastRender = 0
window.requestAnimationFrame(loop)
Upvotes: 3
Reputation: 830
SetInterval will call your function everytime a fix interval of time passes. Like a clock.
SetTimeout will call a function, only once, after a set amount of time passes.
Upvotes: 0