set interval in ionic (Typescript)

The set interval function is an important role to execute the program in a certain interval of time. Whatever code is written in setInterval function that execute at a fixed time. The time range is started from millisecond.

Syntax :

setInterval( callback ,  time)
callback:-  ()=>time:-  We take time in millisecond  E.g(2000)

The example is given below that execute the code on every 2 seconds (2000ms)

setInterval(()=>{
      console.log("Hello world")
//2000 is  millisecond it  means this program print hello world  every 2 second
} ,  2000)

Try other set interval code with a function call

setInterval(()=>{
//call other function whatever you want to execute

intervalcall()
} ,  2000)



function intervalcall(){

console.log("Hello Fellow user")

}

Try other set interval code with a time to start trigger

setInterval(()=>{
if(new Date().getSeconds() == 20){

//In case  date in  minute you use  "new Date().getMinutes"
//In case  date in  hours you use  "new Date().getHours()"
console.log("Hello Fellow users, trigger on  20 seconds")
}
},  1000)

Caution to use setinterval in ionic.

When you are using set interval. it’s executed task on given time but one thing remembers; whenever you do not need so you can clear interval (halt it ) . “clearInterval()” function to be used to remove running “setInterval()” Function.

Example using setInterval with clearInterval .

import { Component } from "@angular/core";
import { NavController } from "ionic-angular";

@Component({
  selector: "page-home",
  templateUrl: "home.html"
})
export class HomePage {
  /*assign varible "t"  as "t : any" and t variable capture the set interval function.
*/
  t: any;

  constructor(public navCtrl: NavController) {
    this.t = setInterval(function() {
      document.getElementById("printgitsof").innerHTML += "<p>gitsof.com</p>";
    }, 10000);
  }

  /*
 Let  assume you have button for halt set interval function on html page     	<button (click)="onClickSubmit()" >
           Halted
         </button>
	<div id="printgitsof"></div>
*/
  onClickSubmit() {
    clearInterval(this.t);
  }
}

Leave a Reply