I'm new to JQuery and Javascript, I try to write a small setTimeout function but it seems not to work. Below is my code, can some one help out by pointing out what is wrong here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>countdown</title>
<script type="text/javascript" src="/jquery-2.1.4.js"></script>
<script>
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setTimeout(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
second--;
}, 1000);
});
</script>
</head>
<body>
<input type="text" id="input" value="25:23"/><br>
<button type="button" id="submit" value="send"></button>
</body>
</html>
Your code executes on .click on the submit button - which means it only executes when you click the button. Also using setTimeout you are only running it once, and by the inner logic of the function it seems you want it to be ongoing. Substitute setTimeout to setInterval to keep it running.
`$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setInterval(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
$('#input').val(minute + ':' + second);
}, 1000);
});`
have to recursive to make call and call again....
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>countdown</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<input type="text" id="input" value="25:23"/><br>
<input type="button" id="submit" value="send"></input>
<script>
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setTimeout(function () {
rece();
function rece(){
if (minute == 0 && second == 0) {
alert("no time left");
console.log('no time left')
}
else if (second !== 0) {
second--;
console.log('second');
rece();
}
else {
minute--;
second = 60;
console.log('minute');
rece();
}
second--;
}
}, 100);
});
</script>
</body>
</html>
I've modified your code slightly and created a fiddle: JsFiddle
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
setTimeout(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
second--;
$('#input').val(minute + ':' + second);
}, 1000);
});
Related
I want to make a piece of code redirect the user to a certain website after 15 is reached by a number. I would use the code below and it would not redirect even if the number is met.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 id="text">please wait <span id="thing" style="font-size: 70px;">0</span> seconds<span id="wait"></span></h1>
<script>
var request = document.getElementById("thing");
var num = 0;
var goup = setInterval(function goUp() {
num++;
request.innerHTML = num;
}, 1000)
var dots = window.setInterval(function dots() {
var waiter = document.getElementById("wait");
if (waiter.innerHTML.length > 5) {
waiter.innerHTML = ""
} else {
waiter.innerHTML += ".";
}
}, 100)
if (num.innerHTML === 15) {
location.href('https://google.com/');
}
</script>
</body>
</html>
Try this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 id="text">please wait <span id="thing" style="font-size: 70px;">15</span> seconds<span id="wait"></span></h1>
<script>
var request = document.getElementById("thing");
var num = 15;
var goup = setInterval(function goUp() {
request.innerHTML = --num;
if (num === 0) {
window.location.href = 'https://google.com/';
}
}, 1000)
var dots = window.setInterval(function dots() {
var waiter = document.getElementById("wait");
if (waiter.innerHTML.length > 5) {
waiter.innerHTML = ""
} else {
waiter.innerHTML += ".";
}
}, 100)
</script>
</body>
</html>
I simply put the if statement inside the interval so it checks every time the 'timer' is updated. Also, I made the timer go backwards because you are telling the user to wait for 15 seconds, so it should be counting down. In addition, I changed location.href() to window.location.href =, since location.href() isn't a function, it's a string, so you need to change it using an assignment operator.
var request = document.getElementById("thing");
var num = 0;
var goup = setInterval(function goUp() {
request.innerHTML = num++;
if (num === 4) {
clearInterval(goup)
location.href = 'https://google.com/';
}
}, 1000)
var dots = window.setInterval(function dots() {
var waiter = document.getElementById("wait");
if (waiter.innerHTML.length > 5) {
waiter.innerHTML = ""
} else {
waiter.innerHTML += ".";
}
}, 100)
I'm having issues using clearInterval to stop my simple count timer once it is equal to 0. Essentially, timer goes past 0 into negative values instead of stopping at 0. I am creating a basic quiz that ideally will alert the user of the correct answers once the timer reaches and stops at 0.
Below is current code:
var count = 10;
var gameTime;
gameTime = setInterval("counter()", 1000);
function convertSeconds(s){
var min = Math.floor(s / 60);
var sec = s % 60;
return min + ":" + sec;
}
function counter(){
count--;
$("#timer").text(convertSeconds(count));
}
if (count === 0) {
clearInterval("#timer");
} else {
//Do nothing
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trivia</title>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div id ="timer">10</div>
</body>
Just move your if check into the counter function and clear the gameTime variable.
setInterval runs the provided function at the given interval so anything you want to run or check on that interval must happen in the provided function.
var count = 10;
var gameTime;
gameTime = setInterval("counter()", 1000);
function convertSeconds(s){
var min = Math.floor(s / 60);
var sec = s % 60;
return min + ":" + sec;
}
function counter(){
count--;
$("#timer").text(convertSeconds(count));
if (count === 0) {
clearInterval(gameTime);
} else {
//Do nothing
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trivia</title>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div id ="timer">10</div>
</body>
What I want to do is have a coin flip which will start a countdown when the flip button is pressed or if instructed to elsewhere. Then I want it to countdown 3, 2, 1 and display that on the screen. When the countdown is complete it will display heads or tails. The reason for this is so I do not have to create an animation of the coin flipping instead a delay to build the tension.
This is the code I have so far:
<html>
<head>
<title>Coin Toss </title>
<script>
function toss() {
if (Math.random()>.5) {
window.document.coin.src = "CT.jpg";
}
else {
window.document.coin.src = "T.jpg";
}
return false;
}
</script>
</head>
<body>
<img name="coin" src="questionmark.png">
<form action="" onSubmit="return toss();">
<input type="submit" value="TOSS">
</form>
</body>
</html>
Here's an example using setTimeout. In this instance I've removed the form as you don't strictly need it imo, and used event listeners so that the JS call is removed from the HTML.
HTML
<img id="coin"/><br/>
<button id="toss">Toss</button><br/>
<div id="count"></div>
JS
function toss() {
var div = document.getElementById('coin');
if (Math.random() > .5) {
coin.src = "CT.jpg";
} else {
coin.src = "T.jpg";
}
}
function countDown() {
var count = 3, timer;
var div = document.getElementById('count');
// if count is not 0, add the new count to the
// count element and loop again, reducing the count number
// otherwise erase the count element, clear the timeout
// and run the toss function
var loop = function loop (count) {
if (count > 0) {
div.textContent = count--;
timer = setTimeout(loop, 1000, count);
} else {
div.textContent = '';
clearTimeout(timer);
toss();
}
}
// start the countdown
loop(count);
}
var button = document.getElementById('toss');
button.addEventListener('click', countDown, false);
DEMO
you can do this with a setInterval, here is an example:
Javascript:
var current = 3;
var elem = document.getElementById('toss');
var intervalId = setInterval( function(){
if( current > 0 ){
elem.innerHTML = "<h1>" + current + "</h1>";
} else {
if( Math.random() > .5 ){
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1932%20Type%201%20Silver%20Washington%20Quarter%20Obv.png">';
} else {
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1988%20Type%202%20Clad%20Washington%20Quarter%20Reverse.png">';
}
clearInterval( intervalId );
}
current--;
}, 1000 ); // 1000 ms = 1s
HTML:
<div id="toss"><div>
Also here is a Fiddle so you can test it out and see what it does:
http://jsfiddle.net/Cedriking/cLs9r3m6/
For your second question (in the comment), do this:
<html>
<head>
<title>This is my title</title>
</head>
<body>
<div id="toss"></div>
<script type="text/javascript">
var current = 3;
var elem = document.getElementById('toss');
var intervalId = setInterval( function(){
if( current > 0 ){
elem.innerHTML = "<h1>" + current + "</h1>";
} else {
if( Math.random() > .5 ){
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1932%20Type%201%20Silver%20Washington%20Quarter%20Obv.png">';
} else {
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1988%20Type%202%20Clad%20Washington%20Quarter%20Reverse.png">';
}
clearInterval( intervalId );
}
current--;
}, 1000 ); // 1000 ms = 1s
</script>
</body>
</html>
Hi all I found a useful bit of JS here:
http://jsfiddle.net/4tj6r/2/
and I am trying to run this as follows but, for some reason I am receiving no output on the webpage - I am a complete newbie so if this is simple many apologies but if there is anyone kind enough out there please point me in the right direction - the code is as follows:
<script type="text/javascript">
$(function() {
var count = localStorage.getItem('count') || 20,
countdown = setInterval(function() {
localStorage.setItem('count', count);
$("p.countdown").html(count + " seconds remaining!");
if (count == 0) {
clearInterval(countdown);
localStorage.removeItem('count');
window.location = 'http://stackoverflow.com/';
}
count--;
}, 1000);
});
</script>
<p class="countdown"></p>
many thanks in advance
All you miss is to call the jQuery library
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function() {
var count = localStorage.getItem('count') || 20;
var countdown;
countdown = setInterval(function() {
--count;
if(count>0){
localStorage.setItem('count', count);
$("p.countdown").html(count + " seconds remaining!");
}else{
clearInterval(countdown);
localStorage.removeItem('count');
window.location = 'http://stackoverflow.com/';
}
}, 1000);
});
</script>
<p class="countdown"></p>
I have an asp.net c# website that I am having a problem getting the jscript to execute.
I have a masterpage that loads that contains the javascript and the code. A code excerpt is below. When it runs, the timer never shows up. If I click the close page button, I get an error that says:
Microsoft JScript runtime error: The value of the property 'closePage' is null or undefined, not a Function object.
on the line:
<input type="submit" name="ctl00$CloseSection$btnClose" value="Close Page Now" onclick="closePage(); return false;" id="ctl00_CloseSection_btnClose" class="buttons" />
I have tried many things, moving the .js src line above and below the var section. NOthing seems to change this. The strange thing is this worked fine just a few days ago. I noticed that MS made several VS updates on 9/14.
Any help would be appreciated.
I can do a view source and the js line shows up fine:
<script src="jscripts/StoreFrontClose.js" type="text/javascript"></script>
The source excerpt is below:
<asp:ContentPlaceHolder ID="CloseSection" runat="server">
<script src="jscripts/PageClose.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var timeoutMins = 0;
var timeoutSecs = 30;
alert("getting ready to start timer");
if (source == "kiosk") {
startPageCloseTimer();
}
<div style="text-align: center;">
The Page will close in: <span id="theTime" class="timeClass"></span>
<br />
<asp:Button ID="btnClose" CssClass="buttons" runat="server" OnClientClick="closePage();"
Text="Close Page Now" />
<asp:Button ID="btnKeepOpen" CssClass="buttons" runat="server" OnClientClick="resetTimer();"
Text="Keep Page Open a little Longer" />
</div>
</asp:ContentPlaceHolder>
the PageClose.js has:
function startPageCloseTimer() {
alertTimerId = setTimeout("AlertUser()", timeoutMilli);
countDown();
}
function AlertUser() {
extend = false;
handleTimerId = setTimeout("HandleTimeout();", maxPopupTime);
jQuery("#messagePopup").dialog("open");
}
function HandleTimeout() {
if (!extend) {
closePage();
}
}
function KeepSessionAlive() {
extend = true;
resetTimer();
}
function resetTimer() {
clearTimeout(alertTimerId);
clearTimeout(handleTimerId);
alertTimerId = setTimeout("AlertUser()", timeoutMilli);
sec = timeoutSecs;
min = timeoutMins;
countDown();
}
function closePage() {
alert("getting ready to close page");
clearTimeout(handleTimerId);
clearTimeout(alertTimerId);
clearTimeout(countDownTimerId);
}
var sec = timeoutSecs; // set the seconds
var min = timeoutMins; // set the minutes
function countDown() {
sec--;
if (sec == -01) {
sec = 59;
min = min - 1;
} else {
min = min;
}
if (sec <= 9) { sec = "0" + sec; }
var time = "";
if (min > 0) {
time = (min <= 9 ? "0" + min : min) + " min and ";
}
time = time + sec + " sec ";
if (document.getElementById("theTime")) {
document.getElementById("theTime").innerHTML = time;
}
countDownTimerId = window.setTimeout("countDown();", 1000);
if (min == '00' && sec == '00') {
sec = "00";
window.clearTimeout(countDownTimerId);
}
}
You simply forgot the closing </script> tag:
<script src="jscripts/PageClose.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var timeoutMins = 0;
var timeoutSecs = 30;
alert("getting ready to start timer");
if (source == "kiosk") {
startPageCloseTimer();
} // end of script
</script> // close tag