Angular 设置超时无效 Javascript
Angular settimeout not working Javascript
我正在从 ngOnInit 调用一个函数,
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')
}
我无法从 set Timeout 函数内部调用 openLearnMoreModal 函数,它给出了一个错误
错误类型错误:_this.openLearnMoreModal 不是函数
问题出在您更改 "this" 引用的超时内,试试这个例子:
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);
}
或者
使用 bind(this)
:
window.onload = resetTimer.bind(this);
window.addEventListener('scroll', resetTimer.bind(this), true);
或 使用arrow function
public idleLogout() {
let t;
const resetTimer = ()=> {
clearTimeout(t);
t = setTimeout(() => {
// this.openLearnMoreModal();
}, 4000);
}
window.onload = resetTimer;
window.addEventListener('scroll', resetTimer, true);
OR 用 this
将其绑定到另一个变量:
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);
}
我正在从 ngOnInit 调用一个函数,
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')
}
我无法从 set Timeout 函数内部调用 openLearnMoreModal 函数,它给出了一个错误
错误类型错误:_this.openLearnMoreModal 不是函数
问题出在您更改 "this" 引用的超时内,试试这个例子:
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);
}
或者
使用 bind(this)
:
window.onload = resetTimer.bind(this);
window.addEventListener('scroll', resetTimer.bind(this), true);
或 使用arrow function
public idleLogout() {
let t;
const resetTimer = ()=> {
clearTimeout(t);
t = setTimeout(() => {
// this.openLearnMoreModal();
}, 4000);
}
window.onload = resetTimer;
window.addEventListener('scroll', resetTimer, true);
OR 用 this
将其绑定到另一个变量:
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);
}