setTimeout and setInterval methods: Ionic 2

Today lets learn how to use JavaScript’s setTimeout and setInterval methods in our Ionic 2 project(which uses Typescript by default).

Related Read:
Basics of Injectable or Providers: Ionic 2

In this tutorial, I’ll be delaying the display of some list items using setTimeout and setInterval methods of JavaScript and will display the company names(as list items) on the home page.

Using setTimeout and setInterval methods: Ionic 2


[youtube https://www.youtube.com/watch?v=dyXZcS8wIWc]

YouTube Link: https://www.youtube.com/watch?v=dyXZcS8wIWc [Watch the Video In Full Screen.]



src/providers/data.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
 
@Injectable()
export class Data {
data: any;
  constructor(public http: Http) {
    this.data = [
      {name: 'Microsoft', code: 324, product: 'Windows 10'},
      {name: 'Apple', code: 678, product: 'iPhone 7'},
      {name: 'Google', code: 567, product: 'Pixel'},
      {name: 'Oracle', code: 89, product: 'RDBMS'},
      {name: 'IBM', code: 542, product: 'Computer Hardware and Software'}
    ];
  }
 
  loadAll(){
      return Promise.resolve(this.data);
  };
}

Here we have an array with couple of objects, which has company name, unique id/code and product details. We also have defined a method loadAll() which returns this.data array as a promise.

src/pages/home/home.html

 < ion-list>
    < ion-item *ngFor="let Company of companies">
      {{Company.name}}
    < /ion-item>
  < /ion-list>

src/pages/home/home.ts: setInterval

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Data } from '../../providers/data';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  companies: any;
  constructor(public navCtrl: NavController, public data: Data) {
    var temp = this;
    var i = 0;
    setInterval(function(){ alert('count '+(i++));
        temp.data.loadAll().then(result => {
            temp.companies =  result;
        });
    }, 3000);
  }
}

Here we do not use this keyword/variable inside setInterval method, as it would reference to setInterval method and not the HomePage class component. So we take a temporary variable temp outside setInterval method and assign this keyword to it. Now using temp variable we can invoke class component properties and methods.

setinterval method keeps calling itself after every set interval of time. It keeps calling itself until it is stopped using clearInterval() method.

    var temp = this;
    var i = 0;
    var id = setInterval(function(){ alert('count '+(i++));
        temp.data.loadAll().then(result => {
            temp.companies =  result;
        });
    }, 3000);
    clearInterval(id);

Similarly, setTimeout method
src/pages/home/home.ts: setTimeout

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Data } from '../../providers/data';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  companies: any;
  constructor(public navCtrl: NavController, public data: Data) {
    var temp = this;
    var i = 0;
    setTimeout(function(){ 
        temp.data.loadAll().then(result => {
            temp.companies =  result;
        });
    }, 3000);
  }
}

Here setTimeout is executed only once after 3 seconds or 3000 milliseconds. To halt or clear the setTimeout event, we can use clearTimeout() method.

    var temp = this;
    var i = 0;
    var id = setTimeout(function(){ 
        temp.data.loadAll().then(result => {
            temp.companies =  result;
        });
    }, 3000);
   clearTimeout(id);

Note:
Make sure to import the page component and service provider in src/app/app.module.ts file.

Variables and Javascript Methods In jQuery

In this video tutorial we shall see how to use variables and javascript methods in jQuery.

In this tutorial, we shall take a image inside our html document. Once the user clicks on this image, we shall use some javascript methods to generate random discounts and display it using alert box.

Note:
var is a keyword to declare variable.
Math.random() generates random numbers between 0 and 1.
Math.floor() is used to round off the floating point number to integer.
alert() is used to show the message stored in the variable in alert box.
+ is concatenation operator.

HTML code
index.html

1
2
3
4
5
6
7
8
9
<html>
 <head><title>Variables and JavaScript Methods: jQuery</title></head>
 <body>
                      <img src="images/aperture.png" width="79" height="79" />
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we are including 1 image.
We have also linked the web page to jQuery library file and our my_script.js file.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
 $(document).ready( function() {
 
   $("img").click( function() {
 
     var discount = Math.floor( Math.random() * 5 ) + 10;
     var msg      = "Discount: "+discount+"%";
     alert(msg);
 
   });
 
 });

Once the web page is loaded, and the user clicks on the image:
Math.random() function generates some random number between 0 and 1, which is multiplied by 5 and the resulting number is then rounded off to a integer number using Math.floor() method.
This number is then added with some string message and is stored inside another variable called msg.
This is passed to alert() method and is displayed on a alert box.

Math.random() and Math.floor() and alert() are javascript functions.

Video Tutorial: Variables and Javascript Methods In jQuery


[youtube https://www.youtube.com/watch?v=IfGmVi3ZuVw]

YouTube Link: https://www.youtube.com/watch?v=IfGmVi3ZuVw [Watch the Video In Full Screen.]



If you want to learn “javascript” visit Javascript Category on our blog.

With this tutorial, you now know that, your javascript knowledge will come handy. If you don’t know Javascript, still you need not worry as we would explain the things we will use in our jQuery tutorial.

Hide / Show Content: XML & DOM

Video tutorial illustrating the mechanism of hiding and unhiding / showing the XML content inside the DIV tag using DOM.

Before proceeding watch:

Display XML Data With DOM( innerHTML ): XML & Javascript

Business card Content
index.html

 Our Business Card!
   
   
Hide Email || Show Email

Here we get the element by its id and set its display style property to none, to hide it from the user. Later when the user clicks on Show link, we remove the display property none and leave it blank.

Video Tutorial: Hide / Show Content: XML & DOM


[youtube https://www.youtube.com/watch?v=CFoBb-4PJ8A]

YouTube Link: https://www.youtube.com/watch?v=CFoBb-4PJ8A [Watch the Video In Full Screen.]



Business card Styling
Style.css

.companyName
{
    font-family: Verdana;
    font-size: 18px;
    color: red;
    display: block;
    padding: 10px;
    margin: 20px;
    background-color: ivory;
    width: 400px;
    border: 5px;
    border-color: gray;
    text-align: left;
}

.Name 
{
    display: block;
    font-weight: bold;
}

.phone 
{
    display: block;
}

.company
{
    display:block;
}

.email
{
    display: block;
    color: Green;
}

This simple feature can be used to hide and unhide user profile information to the search boots or unauthorized users.
By default, set the email and other fields as hidden. Once the user is logged in or is a friend of the person whose profile is being viewed, then allow the person to access data via show function.

Read / Access XML Data With DOM: XML & Javascript

Video tutorial illustrating the manipulation of XML data using DOM [ Document Object Model ]

Using CSS Level 2, we couldn’t change the order in which we would display / access the XML data. To solve that and many more limitations, we make use of DOM.
In this tutorial you can learn, accessing the required XML content and arrange it as you need it.

Business card Content
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<html>
 <head><title>Our Business Card!</title>
 
  <script language="javascript" type="text/javascript">
 
  function display1() {
 
   var base    = document.getElementById("myBiz");
   var person1 = base.getElementsByTagName("companyName")[0];
   var name = "Name: " + person1.getElementsByTagName("Name")[0].firstChild.data;
   var phLable1 = person1.getElementsByTagName("phone")[0].getAttribute("type") + ": ";
   var phone1 = phLable1 + person1.getElementsByTagName("phone")[0].firstChild.data;
   var phLable2 = person1.getElementsByTagName("phone")[1].getAttribute("type") + ": ";
   var phone2 = phLable2 + person1.getElementsByTagName("phone")[1].firstChild.data;
   var email = "email: " + person1.getElementsByTagName("email")[0].firstChild.data;
   var company;
   comanyy = "Company: " + person1.getElementsByTagName("company")[0].firstChild.data;
 
   alert("Business Card: \n\n" + name + "\n" + phone1 + "\n" 
            + phone2 + "\n" + email + "\n" + company);
  }
 
 
 function display2() {
 
   var base = document.getElementById("myBiz");
   var person2 = base.getElementsByTagName("companyName")[1];
   var name = "Name: " + person2.getElementsByTagName("Name")[0].firstChild.data;
   var phLable1 = person2.getElementsByTagName("phone")[0].getAttribute("type") + ": ";
   var phone1 = phLable1 + person2.getElementsByTagName("phone")[0].firstChild.data;
   var phLable2 = person1.getElementsByTagName("phone")[1].getAttribute("type") + ": ";
   var phone2 = phLable2 + person2.getElementsByTagName("phone")[1].firstChild.data;
   var email = "email: " + person2.getElementsByTagName("email")[0].firstChild.data;
   var company;
   comapany = "Company: " + person2.getElementsByTagName("company")[0].firstChild.data;
 
   alert("Business Card: \n\n" + name + "\n" + phone1 + "\n" 
            + phone2 + "\n" + email + "\n" + company);
 }
 
  </script>
 
 </head>
 <body>
 
 <xml id="myBiz" style="display: none;">
 
 <companynames>
 
  <companyname>
    <name>Satish B</name>
    <phone type="home" primary="call me">(91) 9844552841</phone>
    <phone type="work">(91) 9844119841</phone>
    <email>[email protected]</email>
    <company>Technotip IT Solutions</company>
  </companyname>
 
  <companyname>
    <name>Shwetha</name>
    <phone type="home">(91) 123456789</phone>
    <phone type="work" primary="call me">(91) 987654321</phone>
    <email>[email protected]</email>
    <company>Microsoft</company>
  </companyname>
 
</companynames>
 
 
 </xml>
 
 <a href="javascript:display1()">Satish: Technotip IT Solutions</a><br />
 <a href="javascript:display2()">Shwetha: Microsoft</a>
 
 </body>
</html>

Here we’ve written entire thing in one file, for the purpose of demonstration.
We would highly recommend you to write javascript, css in external file and link it to the html file.

Video Tutorial: Read / Access XML Data With DOM: XML & Javascript


[youtube https://www.youtube.com/watch?v=pJiJWWKEbU0]

YouTube Link: https://www.youtube.com/watch?v=pJiJWWKEbU0 [Watch the Video In Full Screen.]



First we fetch the root tag and assign it to a javascript variable called base. Using this as a reference, we fetch the sub-element and using which we fetch all its child elements and inturn get the data present inside them.

Remember, the string inside the tags Name, phone email and company is also considered separate node.

Inside the index.html file we have taken two anchor tags:
Satish: Technotip IT Solutions
Shwetha: Microsoft

which invoke the javascript functions and then display the information of respective people.

If in case we have hundreds or thousands of people in our XML file, we could use looping and dynamically fetch XML data and display it more meaningfully and with less effort(due to proper programmatical automation).

Moving Image Inside HTML page: Javascript ( A Small Fun Application )

Write a xHTML program to take input from the user and move the image to the corresponding location(position), using Javascript.

Note: ( CSS – Cascading StyleSheet )
Static Positioning does not have top and left properties, so an image which is positioned as Static can’t be moved.
Absolute positioning: The image moves to the new location according to the values of top and left.
Relative positioning: Here the image moves relative to its original position. From its original position, it applies the new top and left value and moves accordingly.

Video Explaining The Code:



YouTube Link: https://www.youtube.com/watch?v=cJtMtd2QmMM [Watch the Video In Full Screen.]



Write a xhtml program, and use the form input tags and accept two values from the user. Using document.getElementById, get those user entered values and assign it to two variables.
Similarly, using the div tags id, change the style information and assign the user entered values to div tags top and left position whenever user hits the “move” button.

Source Code: (move.html)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
<html>
 <head><title> Move Image </title>
 
 <style type="text/css">
  #kids { position: relative; top: 200px; left: 400px; }
 </style>
 
 <script type="text/javascript">
 
  function moveIt()
 {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
 
var kids = document.getElementById("kids").style;
 
kids.top = x + "px";
kids.left = y  + "px";
 
 }
 
 </script>
 </head>
 <body>
 
<form>
X axis: <input type="text" id="x"><br />
Y axis: <input type="text" id="y"><br />
<input type="button" value=" Move " onclick="moveIt()" >
</form>
 
<div id="kids">
  <img 
  src="http://technotip.org/wp-content/themes/NewsDen/images/logo.gif" 
  width="220" height="42">
</div>
 
 </body>
</html>

Fun Application Code:
We have made some minor changes to the above code to get the x and y co-ordinates from the cursor position automatically.

Here, we do not accept input directly from the user. We have removed the html form using html comments(

<!--  Comments -->

) and invoke the javascript function moveIt when the user moves his mouse on the html document.
When there is onmousemove event, most browsers automatically throw some objects and we accept it in our function(as parameter) and make use of it. Some browsers like Microsoft’s Internet Explorer do not throw the event object automatically, so we assign it manually using the below code

   if( !evnt )
evnt = window.event;

Explanation of above two lines of code:
If evnt does not exist, then assign the event to evnt variable.

Also Make Sure To Watch This Video: Event Object: Javascript

Now using the clientX and clientY or screenX and screenY property of the event object, we track the x and y co-ordinates of the cursor and assign that value to the top and left position of the image(div tag which wraps the image tag).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
 
<html>
 <head><title> Move Image </title>
 
 <style type="text/css">
  #kids { position: relative; top: 200px; left: 400px; }
#x, #y { font-size: 24pt; color: red; }
 </style>
 
 <script type="text/javascript">
 
document.onmousemove = moveIt;
 
  function moveIt(evnt)
 {
if( !evnt )
evnt = window.event;
 
var x = evnt.clientX;
var y = evnt.clientY;
 
var kids = document.getElementById("kids").style;
 
kids.top = x + "px";
kids.left = y  + "px";
 
document.getElementById("x").innerHTML = x;
document.getElementById("y").innerHTML = y;
 
 
 }
 
 </script>
 </head>
 <body>
X:<span id="x"></span><br />
Y:<span id="y"></span>
<!--
<form>
X axis: <input type="text" id="x"><br />
Y axis: <input type="text" id="y"><br />
<input type="button" value=" Move " onclick="moveIt()" >
</form>
-->
<div id="kids">
 <img 
 src="http://technotip.org/wp-content/themes/NewsDen/images/logo.gif" 
 width="220" height="42">
</div>
 
 </body>
</html>

Hence, whenever the user move his mouse pointer over the html document the image starts moving according to the new value generated for the each move.