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

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

setTimeout / clearTimeout問題

setTimeout / clearTimeout問題

慕桂英546537 2019-12-20 09:56:58
我嘗試使頁面轉到例如eg之后的首頁。10秒鐘不活動(用戶未單擊任何位置)。我使用jQuery進行其余操作,但測試功能中的設置/清除是純JavaScript。令我沮喪的是,我最終得到了類似該功能的東西,希望我可以在該頁面上單擊任何按鈕。計時器可以正常啟動,但單擊后不會重置。如果在前10秒內調用該函數5次,則將出現5條警報...無clearTimeout ...function endAndStartTimer() {    window.clearTimeout(timer);    var timer;    //var millisecBeforeRedirect = 10000;     timer = window.setTimeout(function(){alert('Hello!');},10000); }有人得到一些可以解決問題的代碼行嗎?-在任何點擊停止時,重置并啟動計時器。-當計時器命中時 10sec做點什么。
查看完整描述

3 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

您需要在函數timer 外部聲明。否則,您將在每次函數調用時獲得一個全新的變量。


var timer;

function endAndStartTimer() {

  window.clearTimeout(timer);

  //var millisecBeforeRedirect = 10000; 

  timer = window.setTimeout(function(){alert('Hello!');},10000); 

}


查看完整回答
反對 回復 2019-12-20
?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

問題在于該timer變量是局部變量,并且在每個函數調用之后其值都會丟失。


您需要持久化它,可以將其放在函數外部,或者如果您不想將變量公開為全局變量,則可以將其存儲在閉包中,例如:


var endAndStartTimer = (function () {

  var timer; // variable persisted here

  return function () {

    window.clearTimeout(timer);

    //var millisecBeforeRedirect = 10000; 

    timer = window.setTimeout(function(){alert('Hello!');},10000); 

  };

})();


查看完整回答
反對 回復 2019-12-20
?
侃侃無極

TA貢獻2051條經驗 獲得超10個贊

在反應中使用此方法:


class Timeout extends Component {

  constructor(props){

    super(props)


    this.state = {

      timeout: null

    }


  }


  userTimeout(){

    const { timeout } = this.state;

    clearTimeout(timeout);

    this.setState({

      timeout: setTimeout(() => {this.callAPI()}, 250)

    })


  }

}

例如,如果您只想在用戶停止輸入后才調用API,則該功能非常有用??梢酝ㄟ^onKeyUp將userTimeout函數綁定到輸入。


查看完整回答
反對 回復 2019-12-20
  • 3 回答
  • 0 關注
  • 573 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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