JSFiddle - React, Tailwind, and code Playground
by ronilan
JavaScript
$.hold = function (milliseconds, params) {
var dfd = $.Deferred();
setTimeout(function () {
dfd.resolve(params);
}, milliseconds);
return dfd.promise();
}
/**
// In short form
$.hold = function (milliseconds, params) {
return $.Deferred(function(dfd) {
setTimeout(function(){dfd.resolve(params)}, milliseconds);
});
}
**/
// demo usage
var x;
x = 10;
// set hold
halt = $.hold(1000, x);
x = 20;
// sent hold and resolve with .then
$.hold(3000, x).then(function (obj) {
console.log("first in code, hold 3000", x, obj, "-->", obj * x);
});
x = 30;
// output with no hold
console.log("second in code, no hold:", x, "-->", x);
x = 40;
// sent hold and resolve with .then
$.hold(2000, x).then(function (obj) {
console.log("third in code, hold 2000", x, obj, "-->", obj * x);
});
x = 50;
// somewhere in the code the first halt resolves
halt.done(function (obj) {
console.log("fourth in code, hold 1000", x, obj, "-->", obj * x);
});
// will output
/**
second in code, no hold: 30 --> 30
fourth in code, hold 1000 50 10 --> 500
third in code, hold 2000 50 40 --> 2000
first in code, hold 3000 50 20 --> 1000
*/
// just something extra
myFunc = function (argA, argB, argC) {
console.log("I'm a function:", argA, argB, argC);
}
// multiple holds, using named hold object, and calling a function as param
$.when($.hold(5000, x), $.hold(500, myFunc), halt).done(function (obj1, obj2, obj3) {
myFunc.call(null, obj1, obj3, x)
})