There are a lot of fundamental problems here.
First, I'm assuming that somewhere not depicted in your code, you're actually calling the wait
function by passing it ms
.
It looks like you want the variables done
and timer
to be accessible in your function _done
. To ensure that, you should init your variables before you define the function.
setTimeout
is async. Javascript is single threaded unless you go out of your way to start up other threads (web workers). setTimeout
will not freeze processing for ms
amount of time. It adds an event that will run if nothing else is executing. Because it is not blocking, your while loop will loop again to create another timeout, and another... ad infinium. None of the many timeouts will interrupt the while loop because of its single threaded nature. It's more like the Windows Message Queue. Since _done
doesn't interrupt and set done
to true, it'll continually spin off more and more timeouts until an inevitable crash.
If you're wanting to delay code execution by a certain amount of time, you setTimeout
once and execution will begin after that wait as long as nothing else is executing.
function _done() {
alert('done!');
}
setTimeout(_done, 1000);
Another note, I don't think you have to clearTimeout
for a timeout that has already timed out. Its only used to prevent a timeout from happening before it times out. This means that nine times out of ten, you can ignore the return value of setTimeout.