I'm trying to create a dynamic live counter.
The counter needs to:
1. It does not stay between 1 and 10. I thought
2. It changes at a constant rate of 2 seconds because of
3. It is displayed individually, meaning every customer sees a different number and refreshing the page restarts the counter from a random number. Is it possible to display the counter globally?
4. It doesn't work when I add it to my website. For some reason
The counter needs to:
- have some text before and after.
- change live.
- stay between 1 and 10.
- change only by ±1.
- have 2 to 10 second intervals between each update (Random but no longer than 10 and no less than 2 seconds between each update).
- if possible, be displayed globally, not individually (All website visitors should see the same exact number at the same exact time).
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="counter-area">I have a <span id="counter"></span> inch pencil</div>
</body>
<script>
function r(t,r){return Math.floor(Math.random()*(r-t+1)+t)}var interval=2e3,variation=1,c=r(1,10);$("#counter").text(c),setInterval(function(){var t=r(-variation,variation);c+=t,$("#counter").text(c)},interval);
</script>
</html>
1. It does not stay between 1 and 10. I thought
c=r(1,10)
would set the min and max but it doesn't. How can I prevent the counter from going above 10 and below 1?2. It changes at a constant rate of 2 seconds because of
interval=2e3
. How can I set the interval to be random but no longer than 10 and no less than 2 seconds between each update?3. It is displayed individually, meaning every customer sees a different number and refreshing the page restarts the counter from a random number. Is it possible to display the counter globally?
4. It doesn't work when I add it to my website. For some reason
,$("#counter").text(c)},interval);
causes an error and the counter does not work. The error says "Uncaught TypeError: $ is not a function". (Screenshot of the error). What does it mean and how do I fix it?