return setTimeout 函数的第一个值
return first value from setTimeout function
我有一个大型 setTimeout 函数,它生成每秒变化的动态变量。对于我拥有的其他函数,我想在调用 setTimeout 函数时获得一个变量,因为我想将它用于另一个不包含在其中的函数。所以本质上,我想要我调用的第一个值,我不想打扰 运行.
中的函数
我该怎么做?
基本上:
function schedule() {
<<changingvalue is here>>
setTimeout(function () { schedule() }, 1000);
}
console.log(<<changingvalue at a particular instance>>);
您可以对 return 第一个 setTimeout
完成后的值使用承诺
let a = 1234;
function schedule() {
++a;
return new Promise(r => setTimeout(function () { schedule(); r(a); }, 1000));
}
(async () => {
console.log(await schedule());
})();
或者只是 return 值
let a = 1234;
function schedule() {
++a;
setTimeout(function () { schedule(); }, 1000);
return a;
}
console.log(schedule());
您可以使用 class
。在构造函数中初始化计数,然后调用更新计数的 loop
方法,然后每秒再次调用自身一次。
然后您可以从 class 创建一个新实例,然后在需要时从您的其他函数调用 getCount
。
在这个例子中,我有一个每三秒调用一次 getCount
的间隔,所以你会看到输出:3、6、9 等
class Timeout {
constructor() {
this.count = 0;
this.loop();
}
getCount() {
return this.count;
}
loop() {
this.count = this.count + 1;
setTimeout(this.loop.bind(this), 1000);
}
}
const timeout = new Timeout();
setInterval(() => {
console.log(timeout.getCount());
}, 3000);
我有一个大型 setTimeout 函数,它生成每秒变化的动态变量。对于我拥有的其他函数,我想在调用 setTimeout 函数时获得一个变量,因为我想将它用于另一个不包含在其中的函数。所以本质上,我想要我调用的第一个值,我不想打扰 运行.
中的函数我该怎么做?
基本上:
function schedule() {
<<changingvalue is here>>
setTimeout(function () { schedule() }, 1000);
}
console.log(<<changingvalue at a particular instance>>);
您可以对 return 第一个 setTimeout
完成后的值使用承诺
let a = 1234;
function schedule() {
++a;
return new Promise(r => setTimeout(function () { schedule(); r(a); }, 1000));
}
(async () => {
console.log(await schedule());
})();
或者只是 return 值
let a = 1234;
function schedule() {
++a;
setTimeout(function () { schedule(); }, 1000);
return a;
}
console.log(schedule());
您可以使用 class
。在构造函数中初始化计数,然后调用更新计数的 loop
方法,然后每秒再次调用自身一次。
然后您可以从 class 创建一个新实例,然后在需要时从您的其他函数调用 getCount
。
在这个例子中,我有一个每三秒调用一次 getCount
的间隔,所以你会看到输出:3、6、9 等
class Timeout {
constructor() {
this.count = 0;
this.loop();
}
getCount() {
return this.count;
}
loop() {
this.count = this.count + 1;
setTimeout(this.loop.bind(this), 1000);
}
}
const timeout = new Timeout();
setInterval(() => {
console.log(timeout.getCount());
}, 3000);