setInterval: changing numbers in function depending on times that event has occured

StackOverflow https://stackoverflow.com/questions/23481104

  •  16-07-2023
  •  | 
  •  

سؤال

I need to figure out how to use setInterval() to make text increase 1px(font-size) every 1000 ms. Here's my setup:

    function boom() {
  var fwuff = document.getElementById("fwuff");
  fwuff.style.display="block";
  fwuff.style.textAlign="center"
  setInterval(function(){
    fwuff.style.fontSize=??
  }, 1000);
}

What I don't know is what to put in the fwuff.style.fontSize so I can get the size to increase every time the event occurs. Does anyone understand and know how to do this?

هل كانت مفيدة؟

المحلول

Just use a variable :

function boom() {
    var fwuff = document.getElementById("fwuff");
    var myAwesomeVar = 10; //Base font size
    fwuff.style.display="block";
    fwuff.style.textAlign="center"
    setInterval(function(){
        fwuff.style.fontSize= myAwesomeVar + "px";
        myAwesomeVar++;
    }, 1000);
}

نصائح أخرى

You can use a global variable or get the current fontSize in order to change it. Using a global variable will be slightly more efficient, however if you do not know the size of the font you are changing, you can use the fontSize of the element.

Fiddle

Getting then setting the fontSize:

function boom() {
    var fwuff = document.getElementById("fwuff");
    var myAwesomeVar = 10; //Base font size
    fwuff.style.display="block";
    fwuff.style.textAlign="center";
    setInterval(function(){
       curFontSize = $('#fwuff').css('fontSize');
       FontSizeNumber = parseInt(curFontSize);
       newFontSizeNumber = FontSizeNumber + 1 + 'px';
       $('#fwuff').css('fontSize', newFontSizeNumber);
    }, 1000);
}

or alternatively, you could use a variable:

function boom() {
        var fwuff = document.getElementById("fwuff");
        var myAwesomeVar = 10; //Base font size
        fwuff.style.display="block";
        fwuff.style.textAlign="center";
        fontSizeVar = 12;
        setInterval(function(){
           fontSizeVar++;
           newFontSizeVal = fontSizeVar + 'px';
           $('#fwuff').css('fontSize', newFontSizeVal);
        }, 1000);
    }

Note: the question was tagged jquery. If this was accidental and you want me to convert to traditional JS, just ask.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top