JSFiddle - React, Tailwind, and code Playground
HTML
<p>
How it should/could be:
<div id="test1"></div>
<p>
</p>
How i have to do it:
<div id="test2"></div>
</p>
CSS
#test1, #test2 {
color: green
}
JavaScript
function loadStuff() {
var deferred = $.Deferred()
// do stuff and resolve the deferred at some point
setTimeout(function(){
deferred.resolve()
}, 3000)
return deferred
}
///////////////////////////////
// how it should/could be
// (something like $.Promise.prototype would be nice too)
$.Deferred.prototype.timeout = function(time, fn) {
var timeout = setTimeout(fn, time)
this.always(function(){
clearTimeout(timeout)
})
}
try {
var data = loadStuff()
.timeout(1000, function(){
$("#test1").text("loading...")
})
.then(function(data){
$("#test1").text("got data")
})
}catch(e){
$("#test1").text(e)
}
///////////////////////////////
// how i have to do it
// (at least one way one could do it)
timeoutDeferred = function(deferred, time, fn) {
var timeout = setTimeout(fn, time)
deferred.always(function(){
clearTimeout(timeout)
})
}
var promise = loadStuff()
.then(function(data){
$("#test2").text("got data")
})
timeoutDeferred(promise, 1000, function(){
$("#test2").text("loading...")
})