简体   繁体   中英

How can i add a div based on TIME using js or jquery?

I want to create a timer that will add or remove divs ( inline divs ) based on time function in Javascript or Jquery.

Eg With each second i want to add a div or remove a div.

Can i get some ideas on this?

<html>
    <head>
        <title>Testing</title>
        <script>        
            var i = 0;
            var myVar=setInterval(function () {myTimer()}, 1000);

            function myTimer()
            {
                document.getElementById('Container').innerHTML += "<div id='"+i+"'>This is the Div with New ID 'i'</div>";
                i++;
            }
        </script>
    </head>
    <body>
        <div id='Container'>

        </div>
    </body>
</html>

This Should Create a DIV each second inside the Div with id 'Container'

Use setInterval .

var diff = 1000, // how long between adds in milliseconds
totalTime = 0, // how long we have run
maxTime = 1000*60*60*5, // how long we want to run
interval = setInterval(function() {
  $(".parentDiv").append($("<div>new div</div>"));
  totalTime += diff; // keep track of all of our time
  if (totalTime >= maxTime) {
     clearInterval(interval);
  }
},diff);

Note that the time is in milliseconds.

And to get rid of it

clearInterval(interval);

Beware that it will keep running, and if any of your actions take too long or slow down, you could find yourself with quite the mess stumbling over each other.

You can make use of setTimeout(function, mili seconds)

var testTimer;
function timer()
{
    // Do your stuff
   testTimer = setTimeout("timer()",1000);

}

This will call your timer function every one second. and you can do your stuff in this function

To stop this timer function you can do

window.clearTimeout(testTimer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM