【发布时间】:2018-03-26 09:11:53
【问题描述】:
我想每 1 秒运行一次函数。经过搜索,我找到了setInterval,但它对我不起作用。
setInterval(function(){
this.myfuntion();
}, 1000);
我也试过this.myfuntion,但也没用。
【问题讨论】:
标签: javascript angular typescript ionic2 ionic3
我想每 1 秒运行一次函数。经过搜索,我找到了setInterval,但它对我不起作用。
setInterval(function(){
this.myfuntion();
}, 1000);
我也试过this.myfuntion,但也没用。
【问题讨论】:
标签: javascript angular typescript ionic2 ionic3
我是这样使用的:
import {interval, Subscription} from 'rxjs';
const source = interval(30000);
this.subscription = source.subscribe(val => {
// TODO
});
您可以在构造函数或函数内部使用它,然后从外部调用它。
【讨论】:
对于任何为此苦苦挣扎的人,您可以使用 rxjs 中的 interval,如下所示:
import { interval } from 'rxjs';
interval(1000).subscribe(x => {
this.myfuntion();
});
【讨论】:
基本上有两种方法可以做到这一点。
尝试使用最适合您要求的 observable。
方法一:
import {Observable} from 'Rxjs/rx';
import { Subscription } from "rxjs/Subscription";
// if you want your code to work everytime even though you leave the page
Observable.interval(1000).subscribe(()=>{
this.functionYouWantToCall();
});
方法二:
// if you want your code to work only for this page
//define this before constructor
observableVar: Subscription;
this.observableVar = Observable.interval(1000).subscribe(()=>{
this.functionYouWantToCall();
});
ionViewDidLeave(){
this.observableVar.unsubscribe();
}
【讨论】:
解决方法是使用Arrow functions:
setInterval(() => {
this.myfuntion(); // Now the "this" still references the component
}, 1000);
使用箭头函数时,this 属性不会被覆盖,仍会引用组件实例。
【讨论】:
试试这个。我认为这是一个范围问题。没有绑定 setInterval 中的作用域就转到窗口对象
setInterval(function(){ this.myfunction();}.bind(this), 1000);
【讨论】: