Raja
Raja

Reputation: 3627

Javascript: Execute a function for every 3 seconds for One minute

I need to execute a function for every 3 sec upto 1 minutes. This should be called when a user focus on the input box.

I have tried by Googling but most of them come-up with setInterval function. I knew that the setInterval can be used to call a function for certain time interval. But i need to stop that if the time reaches 1 min.

Please suggest me on this.

Upvotes: 2

Views: 1125

Answers (2)

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try like this -

var time = 0;
var interval = setInterval(function(){
    // do your stuf
    time += 3000;
    if(time >= (1000*60)){ // one minute
      clearInterval(interval);
    } 
},3000);

Working Demo

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82251

Try this on input focus of textbox:

var startTime = new Date().getTime();
var interval = setInterval(function(){
if(new Date().getTime() - startTime > 60000){
    clearInterval(interval);
    return;
}
//do whatever here..
}, 3000); 

Working Demo

Demo Code:

$('input').one('focus',function(){
var startTime = new Date().getTime();
var interval = setInterval(function(){
if(new Date().getTime() - startTime > 60000){
  clearInterval(interval);
  alert('interval cleared');
return;}console.log('test')}, 3000);})

Upvotes: 2

Related Questions