user1469270
user1469270

Reputation:

Use setInterval() with jQuery to change div content

Every 2 seconds, I want some content to change. At the moment, I have:

 setInterval(function() {
    $('.timer').text(3+3);
}, 2000);

However, it just replaces the current text of .timer with the number 6. I want it to continue adding 3+3 to the existing number, so 6 + 3 + 3.

JSFIDDFLE

I'm using this as a learning exercise, so any additional help would be appreciated.

Upvotes: 0

Views: 1158

Answers (4)

niko
niko

Reputation: 9393

Since you have specified 6 + 3 + 3 I guess your interested to add 6? 3+3 results 6 anyways?

setInterval(function() {
   var i = +$('.timer').text() ; // + converts the string to int
   i +=6; // add 6 as you have mentioned 3+3
   $('.timer').text(i); // update the inerText
}, 2000);

Demo http://jsfiddle.net/Xqnam/5/

Upvotes: 0

semirturgay
semirturgay

Reputation: 4201

here is demo

var count=3;
setInterval(function() {
    $('.timer').text(""+parseInt($('.timer').text())+count);
    count+=3;
}, 400);

Upvotes: 0

adeneo
adeneo

Reputation: 318252

As 3 + 3 = 6, that's no suprise, if you want strings, quote them

setInterval(function() {
    $('.timer').text(function(_, txt) {
        return txt + '3';
    });
}, 2000);

FIDDLE

EDIT:

If you're trying to add numbers, you can do:

setInterval(function() {
    $('.timer').text(function(_, txt) {
        return parseInt(txt,10) + 3;
    });
}, 400);

FIDDLE

Upvotes: 3

Ehtesham
Ehtesham

Reputation: 2985

As far as I took it you want to add 3 to existing content. Here's the way to go

setInterval(function() {
    var oldContent = parseInt($('.timer').text(), 10);
    $('.timer').text(oldContent + 3);
}, 2000);

Fiidle

Upvotes: 0

Related Questions