Pullapooh
Pullapooh

Reputation: 161

switch between text for 5sec or 50 times

How would I build a simple text changer with jQuery. I have a <h1> </h1> on my page and I would like to change text every half a second between two words (yes) and (no). For a period of 5 seconds or for 50 times.

The idea is that the text would rapidly change from yes to No = Yes...No...Yes...No...Yes...No...

var i = 0;
while ( i < 100 ) {
    // This block will be executed 100 times.
    $('h1').append("Yes");
    $('h1').append("No");
    i++; // Increment i
}

I know that I need to use a counter but I don't know the best way of creating the change.

Upvotes: 0

Views: 89

Answers (4)

E. S.
E. S.

Reputation: 2919

Use a interval

Try this: (http://jsfiddle.net/Yatnw/1/)

Html

<h1>yes</h1>

Js

var count = 0,timer=0;
var myTimer = setInterval(function(){
    var text = ( count % 2 ) ? 'yes' : 'no';

    count = count+1;
    timer = timer + 0.5;

    $('h1:first').text( text );

    if( count > 50 || timer >= 5){
        clearInterval(myTimer);
    }
},500);

Upvotes: 1

Michael Tempest
Michael Tempest

Reputation: 834

You should use a recursive timeout pattern as setInterval methods can introduce uneccesary memory leaks.

var count = 0;

(function loopsiloop(){
   setTimeout(function(){
       $('h1').html(msg(count));

       if(count < 50) {
           ++count;
           loopsiloop();
       }
   }, 500);
})();

msg = function (count) {
    if (count % 2) {
        return 'yes';
    }  else {
        return 'no';
    }
};

http://jsfiddle.net/Lcyev/

To see why we should use this over the setInterval method please take a look at the jsperf tests here http://jsperf.com/setinterval-vs-recursive-settimeout and for further reading https://www.google.co.uk/search?q=settimeout+vs+setinterval&oq=set&aqs=chrome.1.69i57j69i59j69i60j0l3.3488j0j7&sourceid=chrome&espv=210&es_sm=91&ie=UTF-8#es_sm=91&espv=210&q=recursive+settimeout+vs+setinterval

Upvotes: 1

Irvin Dominin
Irvin Dominin

Reputation: 30993

Try using a recursive setTimeout, and clear it after it end the execution

Code:

var timer = null;
var startTime = new Date().getTime();

setTimeout(function () {
    updatetimer()
}, 500)

var updatetimer = function () {

    if (new Date().getTime() - startTime > 5000) {
        clearTimeout(updatetimer);
        return;
    }

    if (!$('h1').hasClass('yes')) {
        $('h1').append("Yes").addClass('yes');
    } else {
        $('h1').append("No").removeClass('yes');
    }

    timer = setTimeout(updatetimer, 500);
};

Demo: http://jsfiddle.net/IrvinDominin/ewe3D/

Alternatively you can use a setInterval with similar rules.

Code:

var startTime = new Date().getTime();
var interval = setInterval(function () {
    if (new Date().getTime() - startTime > 5000) {
        clearInterval(interval);
        return;
    }
    if (!$('h1').hasClass('yes')) {
        $('h1').append("Yes").addClass('yes');
    } else {
        $('h1').append("No").removeClass('yes');
    }
}, 500);

Demo: http://jsfiddle.net/IrvinDominin/8hfNp/

Upvotes: 0

Jamiec
Jamiec

Reputation: 136074

One easy way to do this is to use setInterval which keeps repeating until you clear the interval

var text = ["Yes","No"];
var i =0;
var interval = setInterval(function(){
    $('h1').text(text[i%2]);
    i++;
    if(i == 50)
        clearInterval(interval);
},500);

Live example: http://jsfiddle.net/jamiec/YT2u7/

If you're worried about the potential for errors in the above code (I wouldn't be with something this simple) then you can do a similar thing with setTimeout but it requires you to call the function again at the end.

var text = ["Yes","No"];
var i =0;

function update(){
    $('h1').text(text[i%2]);
    i++;
    if(i<50)
        setTimeout(update,500);
}

update();

Live example: http://jsfiddle.net/jamiec/F6z35/

But as I commented

50 times with an interval of 500ms is not 5 seconds, its 25 seconds

Upvotes: 2

Related Questions