Clearing an interval - javascript

I'm studying Javascript and I'm having difficulties and understanding why a piece of code (see below) I edited doesn't work. The purpose is pretty simple - I want to create a button that stops and runs time back again. I even printed text to be sure my code enters the 'if' and 'else' statements, but the clearInterval doesn't seem to work. Help much appreciated!
(*the original code belongs to w3schools, I have added the "loop function" just to see if it would work, and it doesn't ;( )
This is the code:
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="checkTime()">Stop time/Start time again</button>
<p id="test"></p>
<script>
var myCounter = 0;
var myVar = setInterval(myTimer ,1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
function checkTime() {
myCounter += 1;
if (myCounter == 1) {
clearInterval(myVar);
document.getElementById("test").innerHTML = "ok";
} else {
var myVar = setInterval(myTimer ,1000);
myCounter = 0;
document.getElementById("test").innerHTML = "clicked again";
}
}
</script>
</body>
</html>
Thanks!

Remove the var from the second var myVar = setInterval...
The second one is scoped to your function and "overrides" the first one...
function checkTime() {
myCounter += 1;
if (myCounter == 1) {
clearInterval(myVar);
document.getElementById("test").innerHTML = "ok";
} else {
myVar = setInterval(myTimer ,1000);
myCounter = 0;
document.getElementById("test").innerHTML = "clicked again";
}
}

Just glanced at your code quickly, but I notice that you are redeclaring your myVar variable, which is the variable that is being cleared when you call clearInterval due to a funky feature in javascript called hoisting.
Try the following...
<script>
var myCounter = 0;
var myVar = setInterval(myTimer ,1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
function checkTime() {
myCounter += 1;
if (myCounter == 1) {
clearInterval(myVar);
document.getElementById("test").innerHTML = "ok";
} else {
myVar = setInterval(myTimer ,1000);
myCounter = 0;
document.getElementById("test").innerHTML = "clicked again";
}
}
</script>

Related

Executing two functions in the same onclick event but running one only once

I'm trying to get an image to run two javascript functions at the same time, the problem is that I want the changeImg() function to run continually with each click but only execute the clock() function once. (So that it starts the timer).
<img id="emotion" src="Target.jfif" width="50" onclick="changeImg();clock(); this.onclick=null;"/>
This is my changeImg() script:
{
var x = Math.floor(Math.random()*900);
var y = Math.floor(Math.random()*900);
var obj = document.getElementById("emotion");
obj.style.top = x + "px";
obj.style.left = y + "px";
}
And this is my clock() script:
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 30;
function myClock() {
document.getElementById("demo").innerHTML = --c;
if (c == 0) {
clearInterval(myTimer);
alert("Reached zero");
}
}
}
Have clock() check if the timer is already set, and return.
function clock() {
if (myTimer) { // clock already started
return;
}
myTimer = setInterval(myClock, 1000);
var c = 30;
function myClock() {
document.getElementById("demo").innerHTML = --c;
if (c == 0) {
clearInterval(myTimer);
alert("Reached zero");
}
}
}
instead of passing null to onclick pass the function changeImg
onclick="changeImg();clock();this.onclick=changeImg;"
I don't know about good practices but it works without changing your code too much

I can't make my timer on javascript to redirect to another page

I'll try to be brief.
I know practically nothing about programming, I'm trying to learn by myself for a personal project.
I'm trying to do something like a timer which, when it reaches 0, redirects to another page. What I managed to build so far is this:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="txt">
<body onload="startCount()">
<script>
var c = 10;
var t ;
var timer_is_on = 0;
function timedCount() {
document.getElementById("txt").value = c;
c = c - 1;
t = setTimeout(timedCount, 1000);
}
function startCount() {
if (!timer_is_on) {
timer_is_on = 0;
timedCount();
}
}
</script>
</body>
</html>
When I try it on chrome, it doesn't run or it instantly jumps to the other page.
If you could tell me what's wrong, or how to fix it, it would be wonderful.
Now, I just discover(?) that I lost the other part that redirects. I used this
<script>
function myFunction() {
location.replace("https://www.w3schools.com")
}
</script>
I don't know if I explained this correctly, but I appreciate the help!!
Thanks!
EDIT: Thanks everyone for the answers!! It's fixed now.
I think what you are trying to do is update the value of timer in the input box every second until it reaches zero, and after that redirect to another URL.
This would do the needful:
(I have removed some unused code which is not required)
<!DOCTYPE html>
<html>
<body>
<input type="text" id="txt" />
<body>
<script>
var timeLeft = 10;
function timedCount() {
document.getElementById("txt").value = timeLeft;
if (timeLeft) {
setTimeout(function(){
timeLeft--;
timedCount();
}, 1000);
} else {
window.location = 'https://w3schools.com';
}
}
timedCount();
</script>
</body>
</html>
In the timedCount check if the value of C is bigger than 0 and run setTimeout otherwise (smaller or equal 0) redirect
Also I think you meant to update timer_is_on to 1 here:
function startCount() {
if (!timer_is_on) {
timer_is_on = 0; //Shouldn't this be set to 1?
timedCount();
}
}
I believe this could be one of the ways to do it.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="txt">
<body onload="startCount()">
<script>
var c = 10;
var t ;
var timer_is_on = 0;
function timedCount() {
document.getElementById("txt").value = c;
c--;
t = setTimeout(timedCount, 1000);
if(c <= 0) {
window.location.href = "https://www.w3schools.com/";
}
}
function startCount() {
if (!timer_is_on) {
timedCount();
}
}
</script>
</body>
</html>

Little mistake somewhere. Help needed

I wrote a little browser-game.
The rules are easy: you have 15 seconds to decide if you know the name written on the screen.
You have two buttons: "i know"/"give up" - depends on what you want to choose.
If you choose "give up" (or time ends) photo 1 appears. Otherwise, photo 2 will be shown.
Whole operation is looped.
Here's my question: I wanted to choose random name from array "word" every single round, so I wrote function "random_word()". I put it into "timer()", "surrender()" and "winning()" functions. But it doesn't work.
I'm just starting with programming, so I'll be grateful for possibly easiest to understand code. Thanks for all help.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<button id= "btnSurrender">give up</button>
<button id= "btnWinning">i know</button>
<p id="seconds">15</p>
<div id="photo"></div>
<script type="text/javascript">
var word = new Array(3);
word[0] = "Michael";
word[1] = "Simon";
word[2] = "Peter";
word[3] = "Mark";
function random_word(){
var randomWord = word[Math.floor(Math.random()*word.length)]
}
var btn1 = document.getElementById("btnSurrender");
var btn2 = document.getElementById("btnWinning");
var pic = document.getElementById("photo");
var secondsP = document.getElementById('seconds');
var clock = null;
btn1.addEventListener("click", surrender);
btn2.addEventListener("click", winning);
function timer () {
random_word();
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
pic.innerHTML='<img src="" alt="">';
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
pic.innerHTML='<img src="mops bops.png" alt="">';
}
}, 1000);
}
function surrender(){
clearInterval(clock);
pic.innerHTML='<img src="mops bops.png" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
function winning(){
clearInterval(clock);
pic.innerHTML='<img src="mopsik.jpg" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
timer();
document.write(randomWord)
setInterval(timer, 17000)
</script>
</body>
</html>
var randomWord;
You need to arrow it at the beginning of the script, before giving a document.write
When I tested your code and set it to the "randomWord" variable at the beginning of the code, it worked; You should do the same, set the variable at the beginning of the code!

Javascript show variable every 50 ms

I want to make a little 'loading...' widget for my website, using javascript.
var percent=0;
var message="Loading... "
var per="%"
function count(){
percent=percent+1;
if(percent==100){
alert("Loading end.")
}else{
setTimeout("count",50)
document.write(message)
document.write(percent)
document.write(per)
}
But it isn't running. I think I've got some mistake (or maybe totally wrong). How can I do this? I want to update the shown message every 50ms.
try with interval and clear it when progress is finished:
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="progress">MSG</div>
<script type="text/javascript">
var percent = 0;
var message = "Loading... ";
var per = "%";
var dom = document.getElementById('progress');
var iv = setInterval(function(){
console.log(message);
dom.innerHTML = ((percent++) + per +' '+ message);
if(percent === 100){
console.log("Loading end.");
clearInterval(iv);
return false;
}
}, 50);
</script>
</body>
</html>
try
setInterval(count,50);
instead of setTimeOut("count",50)
You want to set an interval which runs every x milliseconds, passing in an anonymous function to call the function to call
var percent=0;
var message="Loading... "
var per="%"
function count(){
percent=percent+1;
if(percent==100){
alert("Loading end.")
}else{
setInterval(function() { count() },50)
document.write(message)
document.write(percent)
document.write(per)
}
} <--- you were also missing this ending brace
Script:
var percent = 0;
var message = "Loading... ";
var per = "%";
$(document).ready(function () {
count();
});
function count() {
percent = percent + 1;
if (percent == 100) {
alert("Loading end.");
} else {
setTimeout(function () {
count();
}, 50);
document.write(message);
document.write(percent);
document.write(per);
}
}
see this fiddle for more http://jsfiddle.net/8nhmU/19/
See this jsfiddle
HTML:
<span id="loading"></span>
Javascript:
var percent = 0;
var message = "Loading...";
var per = "%";
var element = document.getElementById('loading');
var interval = setInterval(function() {
element.innerHTML = message + percent + per;
percent += 1;
if(percent > 100) {
clearInterval(interval)
};
}, 50)
The code in your example is missing a great deal of semi-colons and the ending curly-bracket, but that's not the end-issue.
The "problem" with your call to setTimeout is that the first argument must be an actual function, not a string. If you remove the quotes around the call, it will work.
Here is a copy of your code, re-formatted:
var percent=0;
var message="Loading... ";
var per="%";
function count() {
percent++;
if (percent == 100) {
alert("Loading end.");
} else {
setTimeout(count, 50);
document.write(message);
document.write(percent);
document.write(per);
}
}
You are doing it wrong way. You should call the setInterval method when window loads. And when loading is completed, you should stop interval by clearing it using its ID.
var countId;
window.onload = function(){
countId=setInterval(count,50);
}
function count(){
if(per=99){
clearInterval(countId);
}
per++;
//show your message
}

Onclick reset setInterval

<!DOCTYPE html>
<html>
<head>
<script>
function timer(x) {
if (x == 1) {
//reset timer
}
var i = 0;
var timer = setInterval(function() {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 500);
}
</script>
</head>
<body>
<p id="demo">hello</p>
<button type="button" onclick="timer(0)">change</button>
<button type="button" onclick="timer(1)">reset</button>
</body>
</html>
I want to reset timer onclick . e.g. if setIntervaltime is set to 5 sec and 3 seconds are elapsed ,after that if some on click on reset button it should start gain from 5 seconds.How to do this.
Keep the return value of setTimeout somewhere that you can get it again (currently you are storing it in a local variable, so it goes away when the function ends)
Call clearTimeout(timer);
Call setTimeout with whatever arguments you want again.
As already Quentin mentioned, use clearInterval to solve your problem.
Wrap it within an if.else.. statement like
if(x == 1) {
clearTimeout(timeout);
}
else {
timeout = setInterval..... // otherwise even after resetting
// it will continue to increment the value
}
Complete Code:
var timeout; // has to be a global variable
function timer(x) {
var i = 0;
if (x == 1) {
clearTimeout(timeout);
document.getElementById("demo").innerHTML = i;
} else {
timeout = setInterval(function () {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 1000);
}
}
JSFiddle

Categories