mellow-yellow
mellow-yellow

Reputation: 1820

setTimeout and setInterval together -- repeating a pause

In javascript, I need to do the following, written in pseudocode:

REPEAT EVERY 5 SECONDS
    print 'One'
    wait 2.5 seconds
    print 'Two'
    wait 2.5 seconds

How can I do this? My (clumsy?) attempt follows:

a = setInterval(function() { 
     setTimeout(function(){print 'one'},0);
     setTimeout(function(){print 'two'},2500);
    },5000);

Improvements?

Upvotes: 1

Views: 4136

Answers (2)

RobG
RobG

Reputation: 147413

Why you want to combine setTimeout and setInterval for this remains a mystery, but anyhow:

setInterval(function() {
  console.log('one');
  setTimeout(function() {
    console.log('two');
  },2500);
}, 5000);

Upvotes: 3

Joseph Silber
Joseph Silber

Reputation: 219936

var counter = 0;

setInterval(function() { 
     console.log( counter++ % 2 ? 'one' : 'two' );
}, 2500);

Here's the fiddle: http://jsfiddle.net/RvVD7/

Upvotes: 3

Related Questions