简体   繁体   中英

Function setTimeout passed as argument in js class executes immediately, and call class method inside setTimeout

Js class method getInfo should call alert after 5 seconds delay, but it fires immediately

function limiter (limit,hid,sid) {
    this.limit = limit;
    this.hid = hid;
    this.sid = sid;


    this.getInfo = function(aca) {

       setTimeout(alert(aca), 5000);
    };
}


var limiter= new limiter(5,5,5);

limiter.getInfo("loko roko");

Place the alert event inside a function.

 function limiter(limit, hid, sid) { this.limit = limit; this.hid = hid; this.sid = sid; console.log(this.limit); this.getInfo = function(aca) { setTimeout(() => { console.log(this.limit); alert(aca) }, 5000); }; } var limiter = new limiter(5, 5, 5); limiter.getInfo("loko roko"); 

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