Stop a javascript timer and animation and resume them - javascript

I have to stop a timer and an animation of a bar which width is decreasing dependently on a time variable and then resume both if pressed a button, so that the bar animation will continue from where it stopped and the same for the timer. How can I do that?
I can execute a function on button press, it's just the stopping and resuming functions that I don't know.
$("#timebar") is the animated bar.
function startTimer() {
timer = setTimeout(function(){
barAnimation();
}, time);
}
function stopTimer() {
$('#timebar').stop();
$('#timebar').css("width","100%");
clearTimeout(timer);
}
function barAnimation() {
$("#timebar").animate({ width: "0%" }, time, "linear");
}

This doesn't have the animation, but it does offer a start/stop and progress indicator.
var time = 0;
var timer = 0;
var running = false;
function startTimer() {
running = true;
timer = setInterval(function() {
barAnimation();
}, 1000);
}
function stopTimer() {
running = false;
clearInterval(timer);
}
function barAnimation() {
time++;
$("#count").text(time);
$("#timebar").prop("value", time);
}
$("#go").on("click", function(evt) {
if (running) {
stopTimer();
} else {
startTimer();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="go">Go</button>
<progress id="timebar" value="0" max="100"></progress>
<div id="count"></div>

I think something like this is what you're looking for:
var time = 0;
var remaining = 15000;
var interval;
$('#start').click(startTimer);
$('#stop').click(stopTimer);
function startTimer() {
if (!interval) {
interval = setInterval(function(){
if (remaining % 1000 === 0)
$('#time').html(time++);
remaining -= 100;
}, 100); // 100 w/ modulo instead of 1000 for better precision
barAnimation();
}
}
function stopTimer() {
$('#timebar').stop();
clearInterval(interval);
interval = false;
}
function barAnimation() {
$("#timebar").animate({ width: "0%" }, remaining, "linear");
}
#timebar {
background-color: black;
width: 100%;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Start</button>
<button id="stop">Stop</button>
<div id="time">0</div>
<div id="timebar"></div>

Related

How to run pause and stop setInterval

My task:
Run setInterval loop when I hover the current block, for example #main
When I hover on some children element of #main, setInterval has to be paused
After when I leave children element of #main, and return my mouse focus back to #main, setTimeOut should run again. here is screen http://joxi.ru/L215V3qh65weW2
My code:
let num = 0;
var timer = function() { // auto click
{ num >= $(`.the_wrap_graf`).children().length-1 ? num = 0 : num++ }
$(`.year-wrap:eq(${num}) .q`).click()
}
var timerID = null // name of interval
$('.the_wrap_feed').hover(function (ev) { // hover run loop #main
timerID = setInterval(timer, 3000);
}, function (ev) { // mouseleave kill loop
clearInterval(timerID)
})
$(`.q`).mouseenter(function(e) { // kill loop when hover square
clearInterval(timerID)
})
If I add callback to $(.q), it breaks down. How can I do it?
You can't pause an interval timer. You can only cancel it and start a new one.
Re the requirement, I think I'd probably use mouseenter and mouseleave (which you're already doing, using hover) and track whether the cursor is in #main or a child:
var timer = 0;
var timerValue = 0;
var inMain = 0;
var inChild = 0;
function showTimer() {
$("#timer").text(
timer ? "Running: " + timerValue : "Not running"
);
}
function updateTimer() {
if (inMain && !inChild) {
if (!timer) {
timer = setInterval(tick, 100);
}
} else {
if (timer) {
clearInterval(timer);
timer = 0;
}
}
}
function tick() {
++timerValue;
showTimer();
}
showTimer();
$("#main")
.hover(
function() {
++inMain;
updateTimer();
},
function() {
--inMain;
updateTimer();
}
);
$("#main .child")
.hover(
function() {
++inChild;
updateTimer();
},
function() {
--inChild;
updateTimer();
}
);
#main {
border: 1px solid #aaa;
padding: 8px;
}
.child {
border: 1px solid #ddd;
margin: 8px;
}
<div id="timer"></div>
<div>
Not in main
<div id="main">
In main, not in any children
<div class="child">one child</div>
<div class="child">another child</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to stop and resume an interval instead of clearing and recall it?

I got this interval function which adds + 1 every second to this element, and a button which stops it with clearInterval(), but i want to "stop" and "resume" the interval instead of "clear" and restarting it. For example if the interval was stopped with 700 miliseconds, so i want to resume it for runnig from these 700 miliseconds and not from 0.
How can i do that?.
var testingB = $('#testing');
var testingBox = $('.text3');
var counter = 0;
var checker = null;
setInterval( function () { testingBox.text(counter); },1);
var id = setInterval( function () { counter++; },1000);
function adder() {
if (checker === null ) {
clearInterval (id);
checker = true;
testingB.text('Keep Counting');
}
else {
id = setInterval( function () { counter++; },1000);
checker = null;
testingB.text('Stop Couting');
};
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="testing" onclick="adder()"> Stop Counting </button>
<p class="text3"> </p>

Repeating a setInterval

I'm currently using a setInterval function in JavaScript for an HTML page. It has a button that allows me to start a countdown from 10 to 0 with a 1 second interval, and every time I press the button the countdown is supposed to reset. However, after the first button press the next countdown messes up the interval badly.
var count;
function countdown() {
count = 10;
var repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count;
count--;
} else {
clearInterval(repeat);
}
}
<html>
<head>
<title>Page 4</title>
</head>
<body>
<button style=" display: inline-block; " onclick="countdown()">Start Count Down</button>
<div style=" display: inline-block;" id="number"></div>
</body>
</html>
You could use a global variable repeat and reset if set when countdown is invoked.
var count,
repeat;
function countdown(){
count = 10;
if (repeat) {
clearInterval(repeat);
}
repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count;
count--;
} else {
clearInterval(repeat);
}
}
<button style=" display: inline-block; " onclick ="countdown()" >Start Count Down</button>
<div style="display: inline-block;" id="number"></div>
You problem is the repeat variable, it's defined and accessible only inside countdown.
You could just make it global as well, and then you'd have to clear previous intervals when clicking the button again
var count, repeat;
function countdown() {
clearInterval(repeat);
count = 10;
repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count;
count--;
} else {
clearInterval(repeat);
}
}
FIDDLE
put your repeat outside so the function reduce can access it
var count;
var repeat = null;
function countdown(){
count = 10;
repeat = setInterval(reduce, 1000);
}
function reduce() {
if(count > 0)
{document.getElementById('number').innerHTML = count;
count--;}
else
{clearInterval(repeat);}
}
You can also use this to stop interval;
clearInterval(this)
var count;
function countdown() {
count = 10;
var repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count--;
} else {
clearInterval(this);
}
}
<button style=" display: inline-block; " onclick="countdown()">Start Count Down</button>
<div style=" display: inline-block;" id="number"></div>
This will solve your issue but will raise another issue. If you click multiple times, multiple events will be registered. For this, you should either disable button or define repeat in parent scope.
var count, repeat;
function countdown() {
count = 10;
repeat = repeat || setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count--;
} else {
clearInterval(this);
}
}
<button style=" display: inline-block; " onclick="countdown()">Start Count Down</button>
<div style=" display: inline-block;" id="number"></div>
You will notice a simple trick:
repeat = repeat || setInterval(reduce, 1000);
This will ensure multiple intervals are not registered.

FadeIn with javascript without jquery

I have this code:
document.getElementById('showRtb').addEventListener('click', function () {
document.getElementById('rtb').style.display="inline-table";
});
document.getElementById('hideRtb').addEventListener('click', function () {
document.getElementById('rtb').style.display="none";
});
but now I want without jquery effect to make FadeIn animation, just with javascript. Without css3 and without jquery. Is that possible?
You can use setInterval(), getComputedStyle(). See also TheAnimationinterface
var rtb = document.getElementById("rtb"),
timer = null;
document.getElementById("showRtb").addEventListener("click", function() {
if (rtb.style.opacity != 1) {
clearTimeout(timer);
rtb.style.display = "inline-table";
timer = setInterval(function() {
rtb.style.opacity = +rtb.style.opacity + .10;
if (+getComputedStyle(rtb).getPropertyValue("opacity") >= 1) {
clearInterval(timer);
}
}, 100)
}
});
document.getElementById("hideRtb").addEventListener("click", function() {
if (rtb.style.opacity != 0) {
clearTimeout(timer);
timer = setInterval(function() {
rtb.style.opacity = +rtb.style.opacity - .10;
if (+getComputedStyle(rtb).getPropertyValue("opacity") <= 0) {
rtb.style.display = "none";
clearInterval(timer);
}
}, 100)
}
});
#rtb {
width: 100px;
height: 100px;
background: olive;
opacity: 0;
display: none;
}
<button id="showRtb">show</button>
<button id="hideRtb">hide</button>
<br>
<div id="rtb"></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>

Categories