JavaScript Countdown with argument passing in - javascript

You are given an integer called start_num. Write a code that will countdown from start_num to 1, and when the countdown is finished, will print out "Liftoff!".
I am unsure how to do this and keep getting stuck.
This is the code I am provided with at the beginning of the problem:
function liftoff_countdown(start_num) {
// My code goes here!
}
And then they want me to pass in a value such as the 5:
liftoff_countdown(5);
And then this will be my output:
6
5
4
3
2
1
"Liftoff!"
Thanks!

Look at this maybe help you to create your own code
make two file in a same folder (script.js and index.html)
index.html
<!doctype html>
<head>
<title>Countdown</title>
</head>
<body>
<div id="container">
<div id="inputArea">
</div>
<h1 id="time">0</h1>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
var valueRemaining;
var intervalHandle;
function resetPage() {
document.getElementById("inputArea").style.display = "block";
}
function tick() {
var valueDisplay = document.getElementById("time");
valueDisplay.innerHTML = valueRemaining;
if (valueRemaining === 0) {
valueDisplay.innerHTML = "Liftoff!";
clearInterval(intervalHandle);
resetPage();
}
valueRemaining--;
}
function startCountdown() {
var count = document.getElementById("count").value;
if (isNaN(count)) {
alert("Please enter a number!");
return;
}
valueRemaining = count;
intervalHandle = setInterval(tick, 1000);
document.getElementById("inputArea").style.display = "none";
}
// as soon as the page is loaded...
window.onload = function () {
var inputValue = document.createElement("input");
inputValue.setAttribute("id", "count");
inputValue.setAttribute("type", "text");
// create a button
var startButton = document.createElement("input");
startButton.setAttribute("type", "button");
startButton.setAttribute("value", "Start Countdown");
startButton.onclick = function () {
startCountdown();
};
// add to the DOM, to the div called "inputArea"
document.getElementById("inputArea").appendChild(inputValue);
document.getElementById("inputArea").appendChild(startButton);
};
in this example you have many things to understand how javascript works behind scenes.

How about this...
function liftoff_countdown()
{
var span=document.getElementById('num');
var i=document.getElementById('num').innerText;
i=i-1;
span.innerText=i;
if (i==0){
span.innerText='Liftoff!';
clearInterval(count_down)
}
}
var count_down=setInterval(liftoff_countdown,1000);
<span id="num">5</span>

You can achieve this with a simple recursive function and the use of setTimeout to recursively call the function after a time lapse of 1 second.
function lift_off(seconds) {
if(seconds == 0) {
console.log('liftoff');
} else {
console.log(seconds--);
setTimeout(function(){lift_off(seconds);},1000);
}
}
lift_off(10);
Here is a working JSFiddle

Preface
A lot of these answers seem to be focused on doing things with timers and recursion. I do not believe that is your intent. If your only goal is to print those values to the console, you could simply do the following (see the comments for an explanation).
The Answer
function liftoff_countdown(start_num) {
// Loops through all values between 0 and start_num
for(int i = 0; i < start_num; i++) {
// Prints the appropriate value by subtracting from start_num
console.log( start_num - i );
}
// Upon exiting the loop, prints "Liftoff!"
console.log("Liftoff!");
}
Additional Thoughts
You could just as easily loop backwards through the numbers instead of forward like so:
for(int i = start_num; i > 0; i--){
console.log( i );
}
I tend to lean towards iterating forwards just because it's more common, and it's often easy to confuse readers of your code if they gloss over the loop initialization.
Additionally, I am working with the assumption that when you say "print" you mean "console.log()". If this is untrue, you could of course use any other function in its place (e.g. alert( "Liftoff!" );).

Related

Creation of web page to show numbers with intervals

does anyone know how to make a WEB PAGE that shows numbers from, for example, 1 to 100 and that when it reaches 100 it resets to 1 again? and that you can change the time between number and number.
Using html, javascript or anything that was needed. Thx :)
Did you mean something like that?
let countArea = document.getElementById('count-area');
let speedInput = document.getElementById('speed');
let speed = Number(speedInput.value);
function setSpeed() {
speed = Number(speedInput.value)
}
function count() {
if (100 > Number(countArea.textContent)) {
countArea.textContent = Number(countArea.textContent) + 1;
} else {
countArea.textContent = 0;
};
setTimeout(count, speed)
}
count()
speedInput.addEventListener('change', setSpeed)
<!doctype html>
<html>
<head>
<title>Number counter</title>
</head>
<body>
<p id="count-area">0</p>
<input type="range" id="speed" min="50" max="1000">
</body>
</html>
I'm not sure I understand what you mean.
If you mean just a script that writes numbers from 1 to 100 multiple times this can work:
<div id='somediv'></div>
<script>
var times = 4;
for (var n=1;n<times;n++){
for (var i=1;i<101;i++){
somediv.innerHTML+='<br>'+i
}
}
</script>
To set delay between them can add timeout like here:
https://www.w3schools.com/jsref/met_win_settimeout.asp
Depending in what way you want that delay, the rest will be different.
To change how many times it will write 1-100 change the value of 'times', currently it will write it 1 time less then the number(so 3 times), can change that as well.
Edit: Aha!Ok so this can do something similar:
<div id='somediv'></div>
<script>
setInterval(displayCounter, 1000);
var i=0;
function displayCounter() {
document.getElementById("somediv").innerHTML = i;
i=i+1;
if (i==100){i=1};
}
</script>
It will cycle from 0 to 100, then start from 0 again. Currently its 1 second apart(1000 miliseconds). You can make it more or less by changing the 1000 to something else(3000 will be 3 seconds).
Edit 2:
{<br>
"number":"<span id='somediv'></span>"<br>
}
<script>
setInterval(displayCounter, 100);
var i=0;
function displayCounter() {
document.getElementById("somediv").innerHTML = i;
i=i+1;
if (i==100){i=1};
}
</script>
If you want it to start from 1 change:
var i=0;
to
var i=1;
If you want it to be to more or less then 100 change:
if (i==100)...
to 50 for example would be:
if (i==50)...
And can't think of anything more. For style can use css on #somediv.
Edit 3:
{<br>
"number":"<span id='somediv'></span>"<br>
}
<script>
setInterval(displayCounter, 1000);
var i = new Date().getSeconds();
function displayCounter() {
document.getElementById("somediv").innerHTML = i;
i=i+1;
if (i==100){i=1};
}
</script>
This will start the counter(1-100) from the current seconds of the clock. I'm not sure it will be the same for everyone, though, browser may load slower in some places or other factors.
Edit 4:
{<br>
"number":"<span id='somediv'></span>"<br>
}
<script>
setInterval(displayCounter, 1000);
var i = new Date().getSeconds();
if (i>0){somediv.innerHTML = i-1 ;} else if (i==0){somediv.innerHTML = 100}
function displayCounter() {
document.getElementById("somediv").innerHTML = i;
i=i+1;
if (i==100){i=1};
}
</script>

How to set a maximum amount of clicks on an order button for each item specifically? (JavaScript)

I'm trying to implement a functionality where the user can only order a set amount of times (let's take 5 times for example) before an alert shows up saying that the product he is trying to order has ran out of stock.
He can still of course, order other product that haven't been clicked on 5 times.
The problem I'm facing is that I don't know how to keep count of each order button (an anchor acting as a button) specifically.
I tried implementing that functionality and it does show an alert, but it takes count of all order buttons clicked.
This is how my functions looks:
let counter = 0; //global variable
function order_func() {
let every_product= document.querySelectorAll(".all_prods");
for (let each_prod = 0; each_prod < every_product.length; each_prod++) {
every_product[each_prod].addEventListener("click", function (e) {
if(count_stuff < 10){
add_it(e, each_prod); //e to preventDefault() and console.log "each_prod"
count_stuff++;
}else{
out_of_stock(e); //shows the alert it takes the event as argument to prevent default behavior.
}
});
}
}
add_it() is just a function that console.log()'s the product.
I'm only using vanilla JS, I don't want to use any other libraries for this :)
you can use data attribute to store temp values in page. take a look on this example using JQuery.
<!-- index.html -->
Order
<script>
$('#order-btn').click(function() {
var maxCounts = this.data('maxCounts');
var count = this.data('count');
if (count >= maxCount) {
alert('you cant order any more');
return;
}
this.data('count',count++);
// other logic .e.g Ajax call
})
</script>
you can do it using vanilla JS also:
<script>
let counter = 0; //global variable
function order_func() {
let every_product= document.querySelectorAll(".all_prods");
for (let each_prod = 0; each_prod < every_product.length; each_prod++) {
every_product[each_prod].addEventListener("click", function (e) {
var count_stuff = e.target.dataset.count; // or this.dataset.count
var max_count = e.target.dataset.maxCounts; // or this.dataset.maxCounts
if(count_stuff < max_count){
add_it(e, each_prod);
e.target.dataset.count = count_stuff++;
}else{
out_of_stock(e);
}
});
}
}
</script>

javascript: How do I properly loop this function?

I am new to coding with js, and have tried many different ways to loop this code, as well as asking a friend of mine who is a bit more proficient than I am, and he was incorrect as well. I looked up how to use loops in js as well, and I seem to be stumped, so if you could also give me a basic explanation as to how loops in js work, that'd be great!
ORIGINAL CODE
function partA() {
var classes1 = document.getElementsByClassName('_jvpff _k2yal _csba8 _i46jh _nv5lf'); // finds follow button
var Rate1 = classes1[0];Rate1.click(); // clicks button1
}
setTimeout(partB, 20000); // begins func. B about 17 seconds after func a has been completed
function partB() {
var classes2 = document.getElementsByClassName('_de018 coreSpriteRightPaginationArrow'); // finds “next” arrow
var Rate2 = classes2[0];Rate2.click(); // clicks next arrow
}
partA(); // runs functions
The original code itself works fine, but it never seems to work with any loops I use.
Most Recent Loop Attempt
- Note: failed, obviously
function partA() {
var classes1 = document.getElementsByClassName('_jvpff _k2yal _csba8 _i46jh _nv5lf'); // finds follow button
var Rate1 = classes1[0];Rate1.click(); // clicks button1
}
setTimeout(partB, 20000); // begins func. B about 17 seconds after func a has been completed
function partB() {
var classes2 = document.getElementsByClassName('_de018 coreSpriteRightPaginationArrow'); // finds “next” arrow
var Rate2 = classes2[0];Rate2.click(); // clicks next arrow
}
partA(); // runs functions
for (i = 0; i < 30; i++) {
text += “The number is ” + i + “<br>”;
}
Thank you in advance!
- Michael
Any tips to just generally improve the code would also be appreciated.
Still can't work out exactly what you're after (looks like: trying to automate some repetitive task in some page for which you don't control the source)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<title>JS Loop Example?</title>
<script>
function foo() {
var div = $("#x")[0];
div.innerHTML = "foo was clicked";
for (i = 0; i < 5; i++) {
div.innerHTML += "<br />!";
}
setTimeout(function(){ $('.barButton').click() }, 3000)
}
function bar() {
var div = $("#x")[0];
while (div.firstChild) {
div.removeChild(div.firstChild);
}
var wibble = document.createTextNode('bar was clicked');
div.appendChild(wibble);
for (i = 0; i < 5; i++) {
div.appendChild(document.createElement('br'));
wibble = document.createTextNode('?');
div.appendChild(wibble);
}
setTimeout(function(){ $('.fooButton').click() }, 3000)
}
</script>
</head>
<body onload='setTimeout(foo, 3000)'>
<script>
// Up until the close of the body, I can just write into the document.
document.write('<div id="x" class="stuffGoesHere">');
document.write('some random text<br />');
for (i = 0; i < 5; i++) {
document.write('#<br />');
}
document.write('</div>');
document.write('<input type="button" class="fooButton" value="foo" onClick="foo()" />');
document.write('<input type="button" class="barButton" value="bar" onClick="bar()" />');
</script>
</body>
</html>

create simple rotation with pause

How can I cycle through a series of elements, adding a class, pausing then removing the class and moving on to the next element. I have tried setInterval and I have tried setTimeout, but cannot seem to get it to work.
My Javascript
var numpromos = $('.promoteBlock').length;
var promonum = 1;
while (numpromos > promonum){
setInterval(function() {
$('#promoteCont .promoteBlock').fadeOut().removeClass('active');
$('#promoteCont #promo'+promonum).addClass('active');
}
}, 3000);
promonum++;
}
My HTML
<div id="promoteCont">
<div id="promo1" class="promoteBlock">Promotion No.1</div>
<div id="promo2" class="promoteBlock">Second Promo</div>
<div id="promo3" class="promoteBlock">Another one</div>
</div>
function playNext(){
console.log("playNext");
var active = $('#promoteCont').find(".promoteBlock.active");
if( active.length == 0 )
active = $(".promoteBlock:eq(0)");
var fout = active.next();
if( fout.length == 0 )
fout = $(".promoteBlock:eq(0)");
active.fadeOut().removeClass('active');
fout.fadeIn().addClass('active');
setTimeout(function(){
playNext();
},3000);
}
setTimeout(function(){
playNext();
},3000);
http://jsfiddle.net/p1c3kzj7/
Take things out of the while loop. You only need to set the interval once. Perform your state calculation (which item is selected) within the callback method itself. See below, which I believe is what your looking for.
// Global variables to maintain state... I'm sure I'll get some comments about these :p
var numpromos = $('.promoteBlock').length;
var promonum = 1;
$document.ready(function()
{
setInterval(function() {
$('#promoteCont .promoteBlock').fadeOut().removeClass('active');
$('#promoteCont #promo'+promonum).addClass('active');
promonum++;
if(promonums > numpromos)
promonum = 1;
}, 3000);
});

Why isn't this working - JS [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on a project to check to see if a new items is updated on a website. I want to the program to check every second to see if a new item has come in. The items are designated by an ID (which I can get). However, I am having trouble using AJAX to update the part of the website. I want it to 'refresh' the website every second and compare the most recent item to its previous most recent item (i.e. if current > past). Any help would be much appreciated.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.js"></script>
</head>
<body>
<button onclick = "body()">Click Me</button>
<script>
var highest = 0;
var compare = 0;
var creator;
var newItem = false;
var HelpPeople = 'People's Names';
var elements = document.getElementsByClassName('ms-itmhover');
highest = elements[0].getElementsByClassName('ms-vb2')[1].innerText;
var body = function()
{
window.setTimeout(update(), 1000);
}
var update = function()
{
window.jquery-2('body').load('URL');
elements = document.getElementsByClassName('ms-itmhover');
compare = elements[0].getElementsByClassName('ms-vb2')[1].innerText;
creator = elements[0].getElementsByClassName('ms-vb-user')[0].innerText;
if(compare > highest && creaCompare(creator))
{
displayNew();
}
body();
}
var creaCompare = function(create)
{
var comparer = false;
for(var i = 0; i < HelpPeople.length; i++)
{
if(create == HelpPeople[i])
{
comparer = true;
}
}
return comparer;
}
var displayNew = function()
{
confirm('There is a new item');
body();
}
</script>
</body>
I think I asked the question wrong. I am looking to run this on a website (not my own) and have it parse out data and check for new items (AJAX). I am wondering how to use it and how I can use JS on this website (can I run it through the console?)
I rewrote your code because you're using jQuery... but not using it.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.js"></script>
</head>
<body>
<button id="btnTest">Click Me</button>
<script type="text/javascript">
// wait for document loaded
$(function () {
var updateUrl = 'put your update url here';
var highest = 0;
var compare = 0;
var creator;
var newItem = false;
var HelpPeople = 'People's Names';
var elements = $('.ms-itmhover'); // where's this element
highest = $('.ms-vb2', elements).text(); // where are those elements ????
var body = function () {
$('#btnTest").prop('disabled', true);
setTimeout(update, 1000);
};
var update = function()
{
$('body').load(updateUrl, function (response, status, xhr) {
if ( status == "error" ) {
alert("Sorry but there was an error : " + xhr.status + " " + xhr.statusText);
return;
}
elements = $('.ms-itmhover');
compare = $('.ms-vb2', elements).text();
creator = $('.ms-vb-user', elements).text();
if (compare > highest && creaCompare(creator))
{
displayNew();
}
body();
});
};
var creaCompare = function(create) {
var comparer = false;
for (var i = 0; i < HelpPeople.length; i++)
{
if(create == HelpPeople[i]) {
comparer = true;
}
}
return comparer;
};
var displayNew = function() {
confirm('There is a new item');
body();
};
// prevent button click more than once
$('#btnTest").one('click', body);
});
</script>
</body>
As for answering the actual question, without more HTML, there's not much that can be answered. But the above change presumably fixes :
Executing JS code before document is loaded; now wait until page has loaded
Properly make use of jQuery's DOM traversal and manipulation functions.
Better HTML/JS separation
Encapsulate variables in "private" scope (prevent global namespace pollution) (thank you George Mauer)
You had invalid variable names (i.e. jquery-2 is not what you expect, and 2(..) is an invalid syntax)
Your had setTimeout(update(), 1000); which does nothing since it's essentially doing setTimeout(undefined, 1000);
You processed your updated HTML perhaps before it was even loaded (Ajax is async!)
What this answer does not cover :
What is the actual error (the question does not really specify)
Give a concrete working solution, since parts of the HTML is missing
The problem is probably on this line:
window.jquery-2('body').load('URL');
It's not even a valid syntax. It should be written like this:
$('body').load('URL'); // Instead of 'URL' there also should be a proper URL
Also you should know the load function is asynchronous so if you need to do something with loaded elements, you need to put these actions in a callback. (A function passed as a second arguments of the load method.)

Categories

Resources