setInterval is not working as expected - javascript

I have an span element. When hovering it, I expected it to change to hello1 -> hello2 -> hello3 every 1 second, but it is not working like that, why?
i = 0;
$('div').on('mouseenter', function() {
interval = setInterval(function() {
$('div').html('<span>hello' + i +'</span>');
i++;
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span></div>

Your i is incremented outside the setInterval meaning it will only increment on mouseenter. You should also clear the interval each time you mouseenter to avoid lots of intervals going at the same time
i = 1;
var interval;
$('div').on('mouseenter', function() {
clearInterval(interval);
interval = setInterval(function() {
$('div').html('<span>hello' + i + '</span>');
i++;
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>
https://jsfiddle.net/wt73c6bs/
Alternatively if you want the code to only increment on hover and to reset when you stop hovering use the following
i = 1;
var interval;
$('div').hover(function() {
clearInterval(interval);
interval = setInterval(function() {
$('div').html('<span>hello' + i + '</span>');
i++;
}, 1000)
},
function() {
clearInterval(interval);
i = 1;
$('div').html('<span>hello</span>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>
https://jsfiddle.net/wt73c6bs/1/

I think you want to use .append() instead of .html()
i = 1;
var interval;
$('div').on('mouseenter', function() {
clearInterval(interval);
interval = setInterval(function() {
$('div').append('<span>hello' + i + '</span>');
i++;
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>

Here's a simple version with pure JavaScript!
<html>
<head>
<title>STACK OVERFLOW TESTS</title>
<style>
</style>
</head>
<body>
<span>Hello 0</span>
<script>
var innerNumber = 0; // The number that will increments.
var span = document.querySelector('span'); // Adding some reference to the element and event handlers.
span.addEventListener('mouseover', setInterval(changeText, 1000));
function changeText(){
span.innerHTML = 'Hello ' + (innerNumber + 1); // Obtaining the content of the element and adding 1.
innerNumber = innerNumber + 1;
}
</script>
</body>
</html>

Related

How to make clearInterval() work in JavaScript

I want to make an element (id=runner) move across the page by n pixels after a mouseover event, then stop at a certain position (left = 2000px), using setInterval() to repeatedly call move_left(), then clearInterval() when left == 200px. I can make the element move, but when I look in developer tools it never stops - left continues to increase. I am pretty new to JavaScript/HTML/CSS. How do I make it stop?
Relevant code:
<script>
function runner_go()
{
var load_time = performance.now();
const go = setInterval(move_left,20);
}
function move_left()
{
document.getElementById('runner').style.visibility = "visible";
var runner_position = getComputedStyle(document.getElementById('runner')).getPropertyValue('left');
document.getElementById('runner').style.left = parseInt(runner_position,10) + 17 + "px";
if (parseInt(runner_position,10) > 2000)
{
clearInterval(go);
}
}
</script>
</head>
<body style="background-color:gray;" onmouseover = "runner_go();">
<div>
<h1>Running!</h1>
</div>
<img src="images/runner_l.png" alt ="running man" style="position:relative; visibility:hidden;" id = "runner"/>
</body>
You need to create the var 'go' outside the method cause of the scope, also if you let on the 'body' the 'onmouseover' it will set the interval everytime.
Try this code to test:
<head>
<script>
let go = null;
function runner_go()
{
var load_time = performance.now();
go = setInterval(move_left,20);
}
function move_left()
{
document.getElementById('runner').style.visibility = "visible";
var runner_position = getComputedStyle(document.getElementById('runner')).getPropertyValue('left');
document.getElementById('runner').style.left = parseInt(runner_position,10) + 17 + "px";
if (parseInt(runner_position,10) > 2000)
{
clearInterval(go);
}
}
</script>
</head>
<body style="background-color:gray;" onclick = "runner_go();">
<div>
<h1>Running!</h1>
</div>
<img src="images/runner_l.png" alt ="running man" style="position:relative; visibility:hidden;" id = "runner"/> </body>
Problem -
You declared the interval variable as a constant within another function which is not accessible by the move_left function
So just move your interval variable to global scope (outside the function) and it should work
let go;
function runner_go() {
var load_time = performance.now();
go = setInterval(move_left, 20);
}
function move_left() {
document.getElementById('runner').style.visibility = "visible";
var runner_position = getComputedStyle(document.getElementById('runner')).getPropertyValue('left');
document.getElementById('runner').style.left = parseInt(runner_position, 10) + 17 + "px";
if (parseInt(runner_position, 10) > 2000) {
clearInterval(go);
}
}
sample on how intervals and clearIntervals work
let interval, i = 1;
function start() {
interval = setInterval(log, 1000);
}
function log() {
if (i >= 5) clearInterval(interval);
console.log(`Test ${i}`);
i++
}
start();

How to get a working countdown timer with a button that adds +1 to a counter after every click

I am setting up a project for class which I need to use jquery. I have settled on a project whereby you would click the button, the counter would increase by one and a timer would start. This would act like a game to see how fast you can click in 10 seconds.
$("#button").mousedown(function () {
score = score + 1;
startTimer();
});
function startTimer() {
if (stop === 0) {
stop = stop + 1;
var counter = 0;
var interval = setInterval(function () {
counter++;
display = 60 - counter;
$("#button").html("Click! (" + display + " secs)");
if (counter == 60) {
alert("Times up!");
clearInterval(interval);
stop = 0;
endscore = score;
score = 0;
}
}, 1000);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clicks">
<p><span>0</span></p>
</div>
<div class="boxtext">
<p>Time Remaining: <span>10</span> Seconds </p>
</div>
<div class="but">
<button type="button" name="button">Click</button>
</div>
I expected the timer to start and the counter to increase by one but nothing happens at all.
You need to:
Add an id to your button:
<button id="button" type="button" name="button">Click</button>
Also you need to define the score & stop variables globally outside the function:
var score = 0;
var stop = 0;
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var score=0;
var stop=0;
var counter = 0;
var endscore=0;
$("button").mousedown(function () {
score = score + 1;
$("#score").text(score);
startTimer();
});
function startTimer() {
if (stop === 0) {
stop = stop + 1;
var interval = setInterval(function () {
counter++;
display = 60 - counter;
// $("button").html("Click! (" + display + " secs)");
if (counter == 60) {
alert("Times up!");
clearInterval(interval);
stop = 0;
endscore = score;
score = 0;
}
$('#timeRemaining').text(display);
}, 1000);
}
};
});
</script>
</head>
<body>
<div class="clicks">
<p><span id="score">0</span></p>
</div>
<div class="boxtext">
<p>Time Remaining: <span id="timeRemaining">60</span> Seconds </p>
</div>
<div class="but">
<button type="button" name="button">Click</button>
</div>
</body>
</html>
You're using as selector an ID, however your button element doesn't have that ID. You can do the following:
Add the id to that button.
Or, you can change the selector as:
$(".but").mousedown(function() { // or $('button[name="button"]').mousedown(function() {...});
score = score + 1;
startTimer();
});
From your html you didn't have id="button" so use name selector or assign id to the button.
Like below.
$("input[name='button']").mousedown(function() {
score = score + 1;
startTimer();
});
You forgot to initialize some variables and give some ids.
var score = 0
var stop = 0
$("#button").click(function () {
score = score + 1;
startTimer();
});
function startTimer() {
console.log('start timer')
if (stop === 0) {
stop = stop + 1;
var counter = 0;
var interval = setInterval(function () {
console.log('#interval')
counter++;
display = 60 - counter;
$("#button").html("Click! (" + display + " secs)");
if (counter == 60) {
alert("Times up!");
clearInterval(interval);
stop = 0;
endscore = score;
score = 0;
}
$('#counter').html(counter)
}, 1000);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clicks">
<p><span id="counter">0</span></p>
</div>
<div class="boxtext">
<p>Time Remaining: <span>10</span> Seconds </p>
</div>
</div>
<div class="but">
<button type="button" id="button">Click</button>
</div>

counter in seconds idle jquery

i have this function in Idle library, but what i need is to calculate the action time in second, i mean the active time(onclick, onscroll and keypress).
function is:
(function () {
var minutes = false;
var interval = 1000;
var IDLE_TIMEOUT = 5;
var idleCounter = 0;
var counter=0;
document.onclick = document.onkeypress = function () {
idleCounter = 0;
setInterval(function () {
++counter;;
}, 1000);
};
window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
alert(counter);
document.location.href = "SessionExpired.aspx";
}
}, interval);
}());
this function will wait for 5 seconds, if no action on the page, so i will be redirected to SessionExpired.aspx. if there is action, so am doing ++couter each second.
I need when this counter in seconds.
Thank you.
You can just reset the timer
var counter;
var counterSeconds;
document.onclick = document.onkeypress = function () {
idleCounter = 0; // Set counter to 0 on each keypress/page click
clearInterval(counter) // Every time they click, clear the old interval and start a new one below
counter = setInterval(function () { // assign the interval to a variable so we can clear it
if (idleCounter > IDLE_TIMEOUT) { // Check if they've idled too long
document.location.href = "SessionExpired.aspx"; // Redirect them if they have
}
++counterSeconds;
++idleCounter; // Should increment 1/sec depending on your computer.
}, 1000); // Ticks at 1000 milliseconds (1 Second)
};
One problem here is that you start new interval function for each click or keypress event which causes multiple threads to update same variable.
You should start an interval thread outside the event.
try this:
document.onclick = document.onkeypress = function () {
idleCounter = 0;
};
var activeTimer = setInterval(function () {
++counter;
}, interval);
var idleTimer = window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
alert(counter);
document.location.href = "SessionExpired.aspx";
}
}, interval);
This is what i wanted exactly and i did it:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" ></script>
<script src="./e-lawyer/JS/idle.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>timertest</title>
<script language="javascript">
var it;
x = 0;
$(document).ready(function(){
$('.status').html('active');
});
function count() {
x+=1;
$('.usercount').html(x);
}
(function() {
var timeout = 2000;
$(document).bind("idle.idleTimer", function() {
clearInterval(it);
$('.status').html('idle');
});
$(document).bind("active.idleTimer", function() {
it = setInterval(count, 1000);
$('.status').html('active');
});
$.idleTimer(timeout);
})(jQuery);
</script>
</head>
<body>
<div class="status" style="border:1px dashed black; width:500px; height:50px;"></div>
<div class="usercount"style="border:1px dashed black; width:500px; height:50px;"></div>
</body>
</html>

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