简体   繁体   中英

How to create a custom chainable delay function in JavaScript using prototype, IIFE, currying or using new keyword

How can I create a custom chainable delay function in JavaScript using prototype or currying or using new keyword?

Original question is

var foo = function () {
    console.log("bingo!");
};

function bar() {
    console.log("Wow!");
}
// make below two lines work
foo.delay(300); // after 0.3s: "bingo!"
bar.delay(600); // after 0.6s: "Wow!"
// This returns undefined, how to fix it?

My attempt so far.

function delay(time) {
    setTimeout(this, time);
}

var foo = (function () {
    console.log();
    console.log("bingo!");
    return {
      delay: delay.bind(this)
    }
})();

function bar() {
     console.log("Wow!");
    return {
      delay: delay.bind(this)
    }
};

// bar.prototype.delay = function() { return console.log("bar.prototype.delay"); }
foo.delay(300); // after 0.3s: "bingo!"
bar.delay(600); // after 0.6s: "Wow!"

Lastly, can I ask you where would be a good place to study these kind of topics to be more fluent in JavaScript? Thank you in advance.

You have a problem with this code:

setTimeout(this, time); // The first param must be the function to be executed after `n` ms.

Here you need to pass the time value to the function delay , you could pass the implicit arguments array.

return {
  delay: delay.bind(this) // Here you need to pass the `time` value.
}

This is an approach to bind the delay function.

return {
    delay: delay.bind(this, function() {
        console.log("Wow!");
    }, ...arguments)
}

Important: You don't to bind the function delay to pass the context this value. That binding it's necessary if the function delay will use the context this .

 function delay(fn, time) { setTimeout(fn, time); } var foo = (function() { return { delay: delay.bind(this, function() { console.log("bingo!"); }, ...arguments) }; })(); var bar = (function() { return { delay: delay.bind(this, function() { console.log("Wow!"); }, ...arguments) }; })(); // bar.prototype.delay = function() { return console.log("bar.prototype.delay"); } foo.delay(300); // after 0.3s: "bingo!" bar.delay(600); // after 0.6s: "Wow!" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM