Simulate a timed async call
asynchronous, javascript, sleep
Solution
Use `setTimeout()` to schedule something for a future time.
Also, `setTimeout()` is async, your looping is not.
var same = function(str, callback){
setTimeout(function() {
callback(str);
}, 3000);
}
Note: you cannot return a value from the async callback because it's async. The function `same()` completes and returns long before the callback is actually called.
Problem
I'm trying to simulate an async callback, that does something in a set number of seconds. I want these to all log at the same time, 3 seconds from when they are triggered. Right now they log consecutively 3 seconds after each other. The sleep functions are blocking the whole script from running. Any idea why? ``` function sleep(delay) { var start = new Date().getTime(); while (new Date().getTime() < start + delay); } var same = function(string, callback) { new sleep(3000); return callback(string); } same("same1", function(string) { console.log(string); }); same("same2", function(string) { console.log(string); }); same("same3", function(string) { console.log(string); }); ```