setInterval() in js Object

In Javascript, similar to setTimeout(), setInterval method is another window object for timing event. it executes a function or an expression over and over again in a specified number of milliseconds. It returns a numeric ID that can be canceled with the clearInterval() method.

Syntax

var t = setInterval("javascript expression", milliseconds);
clearInterval(t); //cancel the setInterval() ID t 

mouseover to stop
mouseout to go

Typical Use

Repeat Javascript expression in a number of time interval.

var t = setInterval("alert('Hello!')", 1000);

Repeat Javascript fucntionin a number of time interval.Javascript. Stop the function by the method clearInterval().

var t;
function movee() {
    var elem = document.getElementById("box");
    var spot = parseInt(elem.style.top);        
    if (spot < 500) {    
        spot+=2;              
        elem.style.top=spot+"px"; 
    }     
}

t = setInterval(movee,10);
clearInterval(t);

mouseover to stop
mouseout to go

setInterval in js object

Similar to setTimeout, when setInterval is used in the Javascript object, the scope of this keyword refers to changed from the object instance to global object once setInterval is excuted. So we use extended Bind method to keep this keyword in the method to be executed always refers to the object instance.

function div(id) {
this.id = id;
this.t = 0; 
}

div.prototype = {
  
    move: function() {
        var elem = document.getElementById(this.id);
        var spot = parseInt(elem.style.top);        
        if (spot < 1300) {    
            spot+=2;              
            elem.style.top=spot+"px"; 
        }      
    },
    
    go: function(){
        var closure = this.bind(this.move);
        this.t = setInterval(closure,10);    
    },  
    
    bind: function( Method ){
        var _this = this; 
        return(
             function(){
             return( Method.apply( _this, arguments ) );
             }
        );
    }     
}

var m = new div("box1");
m.go();

The setInerval could be extended as repeat().

Social Bookmark if it is useful.