亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲取 setTimeout 函數的結果?

如何獲取 setTimeout 函數的結果?

呼喚遠方 2022-05-26 14:11:16
問題代碼是:var result = 10;function wait(time,f) {  setTimeout(function() {  result = f(result);  }, time);}wait(500, function(x) {return x + 5})wait(250, function(x) {return x * 2})我認為結果是 30,但結果是 25(解決方案)。為什么結果值為 25?
查看完整描述

2 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

您安排兩個回調:


wait(500, function(x) {return x + 5}) // execute after 500ms

wait(250, function(x) {return x * 2}) // execute after 250ms

第一個參數是回調將運行的時間。由于第二個wait調用具有較低的第一個參數,因此它首先運行。


在 250 毫秒左右,從result10 開始,x * 2乘以result2,得到 20。


然后,在 500 毫秒左右,x + 5運行,讓你達到 25。


如果您希望能夠執行此類操作以使代碼看起來更按順序運行,請使用 Promisesawait代替:


let result = 10;

function wait(time,f) {

  return new Promise(resolve => setTimeout(() => {

    result = f(result);

    resolve();

  }, time));

}


(async () => {

  await wait(250, x => x * 2);

  await wait(250, x => x + 5);

  console.log(result);

})();



查看完整回答
反對 回復 2022-05-26
?
慕容森

TA貢獻1853條經驗 獲得超18個贊

如果您希望在 Edge 15 以下,這是一種向后兼容的方式來實現您想要的:


const delay = (()=>{

  let n = 0;

  return (time, func)=>{

    n += time; setTimeout(func, n);

    return delay;

  }

})();

let x = 10;

delay(500, ()=>{

  x += 5;

  console.log(x);

})(250, ()=>{

  x *= 2;

  console.log(x);

});


查看完整回答
反對 回復 2022-05-26
  • 2 回答
  • 0 關注
  • 249 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號