首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >角设置超时不工作Javascript

角设置超时不工作Javascript
EN

Stack Overflow用户
提问于 2018-11-01 21:51:41
回答 2查看 2.4K关注 0票数 1

我正在从ngOnInit调用一个函数,

代码语言:javascript
运行
复制
  public ngOnInit() {
    this.idleLogout();
  }
  public idleLogout() {
    let t;
    window.onload = resetTimer;
    window.addEventListener('scroll', resetTimer, true);

    function resetTimer() {
      clearTimeout(t);
      t = setTimeout(() => {
        // this.openLearnMoreModal();
      }, 4000);
    }
  }
  public openLearnMoreModal() {
    console.log('here')
  }

我无法从设置的超时函数内部调用openLearnMoreModal函数,这会产生一个错误。

错误TypeError:_this.openLearnMoreModal不是一个函数

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-01 21:57:33

问题是在超时内更改" this“引用,尝试下面的示例:

代码语言:javascript
运行
复制
public ngOnInit() {
  this.idleLogout();
}
 public idleLogout() {
  let t;
  const parentThis = this;

  window.onload = resetTimer;
  window.addEventListener('scroll', resetTimer, true); 

 function resetTimer() {

  clearTimeout(t);
    t = setTimeout(() => {
    parentThis.openLearnMoreModal();
  }, 4000); 
 }
票数 3
EN

Stack Overflow用户

发布于 2018-11-01 22:44:48

任一

使用 bind(this)

代码语言:javascript
运行
复制
window.onload = resetTimer.bind(this);
window.addEventListener('scroll', resetTimer.bind(this), true); 

使用arrow function

代码语言:javascript
运行
复制
public idleLogout() {
  let t;
  const resetTimer = ()=> {
      clearTimeout(t);
      t = setTimeout(() => {
      // this.openLearnMoreModal();
      }, 4000); 
    }
  window.onload = resetTimer;
  window.addEventListener('scroll', resetTimer, true); 

使用this将其绑定到另一个变量:

代码语言:javascript
运行
复制
public idleLogout() {
  let t;
  const resetTimer = _resetTimer.bind(this);
  window.onload = resetTimer;
  window.addEventListener('scroll', resetTimer, true); 

 function _resetTimer() {

  clearTimeout(t);
    t = setTimeout(() => {
    this.openLearnMoreModal();
  }, 4000); 
 }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53109861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档