7

My aim is to create identify a piece of code that increments a number by 1, every 1 second:

We shall call our base number indexVariable, I then want to: indexVariable = indexVariable + 1 every 1 second; until my indexVariable has reached 360 - then I wish it to reset to 1 and carry out the loop again.

How would this be possible in Javascript? - if it makes a difference I am using the Raphael framework.

I have carried out research of JavaScript timing events and the Raphael delay function - but these do not seem to be the answer - can anyone assist?

2
12

You can use setInterval() for that reason.

var i = 1;

var interval = setInterval( increment, 1000);

function increment(){
    i = i % 360 + 1;
}

edit: the code for your your followup-question:

var interval = setInterval( rotate, 1000);

function rotate(){
      percentArrow.rotate(1,150,150);
}

I'm not entirely sure, how your rotate works, but you may have to store the degrees in a var and increment those var too like in the example above.

3
  • Can I ask a further question: every 1 second - I wish to carry out the following code every second:{percentArrow.rotate(1,150,150);}. How could I implement this using the above code?
    – JHarley1
    May 14, 2012 at 16:12
  • @JHarley1 you do it the same way. You create a function(){...rotate...} and call it via setInterval( function ,time in ms).
    – Christoph
    May 14, 2012 at 16:16
  • @JHarley1 see my edited post. Note, you can clear the interval anytime calling clearInterval(interval).
    – Christoph
    May 14, 2012 at 16:19
2
var indexVariable = 0;
setInterval(function () {
    indexVariable = ++indexVariable % 360 + 1; // SET { 1-360 }
}, 1000);
2
  • off by one error;) first do module and then increment would be the right way. But nice and compact indeed. I prefer not to write the function directly in the setInterval() though.
    – Christoph
    May 14, 2012 at 16:10
  • What is with the 360? i added it and my value went from 0 to 32 to 62
    – JGallardo
    Jun 23, 2018 at 17:40
0

Try:

var indexVariable = 0;
setInterval(
    function () {
        indexVariable = (indexVariable + 1) % 361;
    }, 1000}

Not the answer you're looking for? Browse other questions tagged or ask your own question.