I'm trying to add a sleep method in a object, which can be called in the middle of a method chain. I considered to use the setTimeout(), but the javascript thread could not be blocked, and it can not output the correct order I want.
<div id="test"></div>
function hello(str){
var text = document.getElementById("text");
this.eat = function(kind){
text.innerHTML += "<p>Eat "+ kind + "</p>";
return this;
}
this.sleep = function(delay){
setTimeout(function(){
text.innerHTML += "<p>Sleep "+delay + "</p>";
}, delay);
return this;
}
text.innerHTML += "<p>Hello, "+ str + "</p>";
return this;
}
var test = hello("guy").sleep(3000).eat("dinner");
/* I want an output as:
Hello, guy -> (wait 3 secs) Sleep 3000 -> Eat dinner
But actually the output is:
Hello, guy -> Eat dinner -> (wait 3 secs) Sleep 3000
*/
Does anyone have any ideas on it? Shoud I use the prototype, or some other ways to deal with it? What's more, if I want to add another method, named sleepFirst
in this object. When I call it like this:
var test2 = hello("boys").sleepFirst(2000).eat("lanch")
it outputs:
(wait 2 secs) sleepFirst 2000 -> Hello, boys -> Eat lanch
What should I do?
(Postscript: I am a beginner in Web Development, maybe someone has asked a similar question before but I had searched for a long time and can't find it out T^T I am a Chinese guy and sorry that my English may seem not so good. Thanks ~~)