I know there are many methods like setTimeout, but I just want a REAL one.
I'm using JavaScript to write a compiler, and I have to find out a way to implement the sleep() function. I know that buggy loop way, it's not what I want.
Thanks.
From the answers above i gather that you want a sleep function that doesnt freeze the browser and doesnt use setTimeout.
Good luck with that, javascript is single threaded. This is NOT possible
You can't, at least in most browser implementations. You'll have to make your compiler work around that. StratifiedJS does something similar.
I'll add some more detail. This, obviously, is not the best way to implement a sleep function, but since you said you're doing a simple drawing language, I'll just go with this:
Imagine you have some code like this:
drawLine(1, 2, 3, 4);
sleep(1000);
drawLine(5, 6, 7, 8);
That could be converted into this by breaking up all the sleeps:
var pieces;
function advance() {
pieces.shift()();
}
pieces=[
function() {
drawLine(1, 2, 3, 4);
setTimeout(advance, 1000);
},
function() {
drawLine(5, 6, 7, 8);
}
];
advance();
Or, if your language is more complex than that, you could do this with more complexity for the compiler (this is the obvious solution):
drawLine(1, 2, 3, 4);
setTimeout(function() {
drawLine(5, 6, 7, 8);
}, 1000);
Again, this may not be applicable if your language gets very complex, but it may be helpful as a starting point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With