Stop timeout when user click and hold the picture - javascript

I have a gallery, that will show pictures to user for 5 to 5 seconds.
function slideSwitch() {
var current = $('#slideshow .active');
current.removeClass('active');
if (current.next().length) {
current.next().addClass('active');
myInterval = setTimeout(slideSwitch, 5000);
bar();
}
}
http://jsfiddle.net/6hcste51/
I'd like to pause the timeout when user click and hold the click on div holder.
For example, the timeout is in 3 seconds, if user click and hold the holder div I'd like to stop in 3 seconds until the hold ends, and then go to 4 and 5 seconds to call the function again.
I saw this function but I don't know how to add it in my slideSwitch(). any ideas?
selector.addEventListener('mousedown', function(event) {
// simulating hold event
setTimeout(function() {
// You are now in a `hold` state, you can do whatever you like!
}, 500);
}

you need to set timer function it can support pause and resume
need to set anmatin can support pause and resume and reset (i use jquery queue &
animations)
At last the code will be :
jsfiddle Link
//--------------------------global variables----------------
var isfirst= true;
var cycle_remaining = null;
var anim_time = 5000;//in mil sec
var downtime = null;
var myTimer = null;
var is_down = false;//is down event
var is_SpeedClick_getnext = false;//set to true you want to set click to get next image
//---------------------------timer-------------------------
function Timer(callback, delay) {
var timerId, start, remaining = delay;
cycle_remaining = remaining;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= new Date() - start;
cycle_remaining = remaining;
};
this.resume = function() {
start = new Date();
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
cycle_remaining = remaining;
};
this.resume();
}
function slideSwitch() {
var current = $('#slideshow .active');
if (current.next().length) {
current.removeClass('active');
current.next().addClass('active');
myTimer = new Timer(slideSwitch, 5000);
resetanim();
startanim();
}
}
//--------------------- mouse control functions----------------------
$(document).on( "click", ".holder", function() {
if(isfirst){
isfirst = false;
slideSwitch();
}
});
$('.holder').on('mouseout mouseup', function(e) {
if(is_down && !isfirst){
is_down = false;
//set this if if you want to set click to get next image
if(downtime > new Date() - 100 && is_SpeedClick_getnext){
slideSwitch();
}else{
myTimer.resume();
startanim();
}
}
});
$(".holder").mousedown(function() {
if(!isfirst){
downtime = new Date();
is_down = true;
myTimer.pause();
puseanim();
}
});
//--------------------- animation control functions----------------------
//start or resume animation
function startanim() {
var myDiv = $( ".bottom_status" );
myDiv.show( "slow" );
myDiv.animate({
width:"100%"
},cycle_remaining );
myDiv.queue(function() {
var that = $( this );
//that.addClass( "newcolor" );
that.dequeue();
});
}
function rutanim() {
var myDiv = $( ".bottom_status" );
myDiv.show( "slow" );
myDiv.animate({
width:"100%"
}, anim_time );
myDiv.queue(function() {
var that = $( this );
//that.addClass( "newcolor" );
that.dequeue();
});
}
//to puse animation
function puseanim() {
var myDiv = $( ".bottom_status" );
myDiv.clearQueue();
myDiv.stop();
}
// to reset animation
function resetanim() {
var myDiv = $( ".bottom_status" );
myDiv.animate({
width:"1%"
}, 200 );
myDiv.queue(function() {
var that = $( this );
that.dequeue();
});
}
.holder{
display:none;
}
.active{
display:block;
}
.bottom_status{
position:absolute;
bottom:0;
background:blue;
width:0%;
height:10px;
left: 0;
margin-left: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id=slideshow>
<div class='holder active'>
Click here to start counting and click and hold to stop.
</div>
<div class='holder'>
text 2
</div>
<div class='holder'>
text 3
</div>
<div class='holder'>
text 4
</div>
</div>
<div class=bottom_status></div>
There is a Var called is_SpeedClick_getnext set to true you want to set click to get next
Note : the explanation in code comment

As mentioned you cant pause a setTimeout, but I have a solution which I think you might find useful.
I've created a second timer function that effectively stores the remaining time before a slide in the #slideshow element as an attribute every 500ms. If the user clicks on an image then it will cancel the original setTimeout and pauses the changing of the #slideshow attribute until the mouseup event. After the mouseup event is fired a new setTimeout is started using the remaining time stored in the attribute.
I also added a line of code to restart from the first image at the end of the slideshow (not sure if that's what you planned).
Hope this helps
// Start slider
slideSwitch();
// Start independent timer
timer();
function slideSwitch() {
// Select active slide and remove active status
var current = $('#slideshow .active');
current.removeClass('active');
// Check if there is a 'next' element and give active class, or return to first
if (current.next().length) {
current.next().addClass('active');
} else {
$("#slideshow img").first().addClass("active");
}
// Reset timer for the slide, store time and reset timer stop
myInterval = setTimeout(slideSwitch, 3000);
$("#slideshow").attr("time", "3000");
$("#slideshow").attr("timeStop", "false");
}
function timer() {
// Check if the slide countdown has been stopped
if ($("#slideshow").attr("timeStop") != "true") {
// Get last saved time and reduce by 500ms
tempTime = parseInt($("#slideshow").attr("time") - 500);
// Save time to slideshow attribute
$("#slideshow").attr("time", tempTime)
// Show countdown on label
$("#timerLabel").text(tempTime);
}
// Continue timer
myTimer = setTimeout(timer, 500);
}
// Add event for mousedown which cancels timer
$("#slideshow img").mousedown(function() {
// Stop timer and clear countdown for slide
$("#slideshow").attr("timeStop", "true");
window.clearTimeout(myInterval);
});
// Start timer on mouse up
$("#slideshow img").mouseup(function() {
// Restart a new countdown for slide using stored time remaining value
tempTime = parseInt($("#slideshow").attr("time"));
myInterval = setTimeout(slideSwitch, tempTime);
$("#slideshow").attr("timeStop", "false");
});
img {
display: none;
border: 5px solid black;
}
img.active {
display: inherit;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="slideshow" time="">
<img src="https://via.placeholder.com/150/fff">
<img src="https://via.placeholder.com/150/000" class="active">
<img src="https://via.placeholder.com/150/f00">
<img src="https://via.placeholder.com/150/0f0">
<img src="https://via.placeholder.com/150/00f">
</div>
<p>Remaining: <span id="timerLabel"></span> ms</p>

Related

issue with if else conditional

When the page is open, it automatically set's a timeout to preform a task.
What i want is to change the timing if an event occur. If the user click a button, it changes the time right after the click.
If the user does nothing, the page should auto refresh after a given time, if the user click on "#b1" , the initial timeout should be interrupted and beggin a new one with other time set
I've tried the previous code, but it only executes the last alert .
How can i accomplish this ?
var clicked = 0;
var time = '';
$('#b1').click(function() {
clicked = 1;
});
if (clicked == 1) {
time = 10;
setTimeout(function() {
alert('clicked');
}, time);
} else {
time = 10000;
setTimeout(function() {
alert('nothingDone');
}, time);
}
Define a global variable where setTimeout is the value, call clearTimeout() with variable as parameter if user clicks #b1 element, then set variable to setTimeout() call within event handler
$(function() {
var clicked = 0;
var time = '';
var timer;
function updateTimer() {
time = 10;
timer = setTimeout(function() {
alert('clicked');
}, time);
}
$('#b1').click(function() {
clicked = 1;
clearTimeout(timer);
updateTimer()
});
if (clicked == 1) {
updateTimer()
} else {
time = 10000;
timer = setTimeout(function() {
alert('nothingDone');
}, time);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="b1">click</div>

toggle the mousemove mousestop event

My question is simple. When my mouse moves, I would like to execute a function which would print "you are moving" in a div tag. When my mouse is not moving, I would like the text function to go away.
Below is a pseudo code that i can think of. So for example, the text function will be called every 50/1000 of a second and check if the mouse is moving. if it is moving, the text will show. if the mouse is not moving, the text will not show. How can i achieve this since there is no mousestop event?
$(function() { setInterval(text, 50);
});
function text() {
/*Do something to check if mouse is moving*/
/*if mouse is moving*/
if{
$("#shu").text("You are moving");
} else {
$("#shu").remove();
}
}
Pure javascript solution:
var shu = document.getElementById("shu");
var timeout;
document.addEventListener("mousemove", function() {
shu.innerHTML = "You are moving";
if (timeout) clearTimeout(timeout);
timeout = setTimeout(mouseStop, 150);
});
function mouseStop() {
shu.innerHTML = "";
}
jsFiddle
You can use jQuery .mousemove function along with set interval to check the mouse movement.
Here is an example code.
var lastTimeMouseMoved = "";
jQuery(document).ready(function(){
$(document).mousemove(function(e){
$(".text").show();
lastTimeMouseMoved = new Date().getTime();
var t=setTimeout(function(){
var currentTime = new Date().getTime();
if(currentTime - lastTimeMouseMoved > 1000){
$('.text').fadeOut('fast');
}
},1000)
});
});
body{
background-color:#333;
}
.text{
display:none;
color:white;
font-size:25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">Your are moving!!</div>
$(window).mousemove(
function() {
$("#shu").text("You are moving");
}, function() {
$("#shu").remove();
}
);
With jquery
var lastMove = new Date().getTime() ,currentTime;
$(window).mousemove(function(){
lastMove = new Date().getTime();
});
setInterval(function(){
currentTime = new Date().getTime();
if(currentTime - lastMove > 400)
$("#shu").empty();
else
$("#shu").text("moving");
},20);
function mouseStop(callback) {
$(window).mousemove((function() {
var t;
return function() {
if(typeof t !='undefined')
clearTimeout(t); //we should check that `t` is not null
t = setTimeout(function() {
callback();
}, 200)//change to 200 so it will not trigger on mouse move
}
})())
}
mouseStop(function() {
console.log("stop!!!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery - interval not executed for the last slide - animation malfunction

I'm creating a slider but using a bunch of divs instead of images. I have 3 divs in total, the first two can move pretty well, but the last one just flies away really fast - it shows for a moment and then moves back to the first div. I just want it to show the same amount of time as the first two. Here's my html code:
<div id="ibToShow">
<div id='sliderWrapper'>
<div class="infoBox" id="infob1">
blablabla
</div>
<div class="infoBox" id="infob2">
blablabla
</div>
<div class="infoBox" id="infob3">
blablabla
</div>
</div>
</div>
And here's my jQuery code:
$(function () {
var width = '55vw';
var showTime = 2000;
var animationSpeed = 500;
var currentDiv = 1;
var $slider = $('#ibToShow');
var $sliderWrapper = $slider.find('#sliderWrapper');
var $infoBox = $sliderWrapper.find('.infoBox');
var interval;
function startSlider() {
interval = setInterval(function () {
$sliderWrapper.animate({'margin-left': '-=' + width}, animationSpeed, function(){
currentDiv++;
if (currentDiv === $infoBox.length){
currentDiv = 1;
$sliderWrapper.css('margin-left', 0);
}
})
}, showTime);
}
function stopSlider() {
clearInterval(interval);
}
$sliderWrapper.on('mouseenter', stopSlider).on('mouseleave', startSlider);
startSlider();
});
I sensed it might be because the animation stopped immediately after the third div showed up. But shouldn't it be waiting for what's set up in showTime?
This problem is still not fixed. Any takers?
You are changing margin left to 0 right after the previous animation ends.
I think this would work better :
function startSlider() {
interval = setInterval(function () {
if(currentDiv++ <== $infoBox.length) {
$sliderWrapper.animate({'margin-left': '-=' + width}, animationSpeed);
}
else {
$sliderWrapper.animate({'margin-left': '0'}, animationSpeed);
currentDiv = 0;
}
}, showTime);
}

Display diffrent image depending on timer

I'm trying to display a different image depending on the timer's result and can't find a way through. So far I have a start and stop button, but when I click stop, I want to use the value the timer is on and display an image(on alertbox or the webpage itself) depending on that value.
if( timer =>60){
img.src("pizzaburnt.jpg");
}elseif (timer <=30){
img.src("pizzaraw.jpg");
}
else{
img.src("pizzaperfect.jpg
}
///Time
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}
//Time stop
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
**HTML**
<td>
Timer :<p id="para">0</p>
</td>
Any advice or dicussion would be great, thanks.
Something like this would work better and it's more compact:
var img = document.getElementById("image");
var imageSrcs = ['pizzaRaw.jpg', 'pizzaPerfect.jpg', 'pizzaBurnt.jpg'];
var imageIndex = 0;
var interval = setInterval(animate, 30000); //change image every 30s
var animate = function() {
//change image here
//using jQuery:
img.src(imageSrcs[imageIndex]);
imageIndex++; //move index for next image
if (imageIndex == imageSrcs.length) {
clearInterval(interval); //stop the animation, the pizza is burnt
}
}
animate();
Reason you wouldn't want to use an increment variable and a 1 second timer is because your just conflating your logic, spinning a timer, and making a bit of a mess when all you really want is the image to change every 30 seconds or whenever.
Hope this helps.
You need an <img> tag in your HTML like this:
<html>
<body>
Timer: <p id="para">0</p>
Image: <img id="image" />
</body>
</html>
And the Javascript code will be like:
var handle;
var timerValue = 0;
var img = document.getElementById( "image" );
var para = document.getElementById("para");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if ( timerValue >= 60 ) {
img.src( "pizzaburnt.jpg" );
}else if ( timer <= 30 ) {
img.src( "pizzaraw.jpg" );
} else {
img.src("pizzaperfect.jpg" );
}
}
function start () {
if ( handle ) {
stop();
}
timerValue = 0;
setInterval( onTimer, 1000 );
}
function stop () {
if ( handle ) {
clearInterval ( handle );
}
}
Please make sure that these 3 files are in the same directory as your HTML file:
pizzaburnt.jpg
pizzaraw.jpg
pizzaperfect.jpg

Show Div on Mouseover after three second

I want on first click it will show after 3 seconds but after the first click when I clicked it will shown before 3 seconds:
function Func1()
{
document.getElementById('div1').style.visibility = "visible" ;
}
function Func1Delay()
{
setTimeout("Func1()", 3000);
}
function Func2Delay()
{
document.getElementById('div1').style.visibility = "hidden" ;
}
Your English or description is very poor, but from what I understand, you want something like this :
var div = document.getElementById('div1'),t;
function changeStyle(element,prop,value){
element.style[prop] = value;
}
function showDiv(){
changeStyle(div,'opacity','1');
}
function hideDiv(){
changeStyle(div,'opacity','0');
}
div.addEventListener('mouseover',function(){
t = setTimeout(showDiv,3000);
},false);
div.addEventListener('mouseout',function(){
clearTimeout(t);
hideDiv();
},false);​
Here's a demo : http://jsfiddle.net/gion_13/TSVA5/
You have to hover the "invisible" div and it will show after 3 seconds.
this works for me
the markup:
<input type="button" value="clickme" onmouseout="ClearIntv()" onmouseover="DelayShow('showMe',5000)" />
<div id="showMe" style="display:none;background-color:red;width:50px;height:50px;">
</div>
the script:
var intv;
function DelayShow(timeOutMs) {
var elm = document.getElementById("showMe");
var now = new Date().getTime();
var end = now + timeOutMs;;
intv = setInterval(function () {
now = new Date().getTime();
if (now >= end) {
elm.style.display = "block";
clearInterval(intv);
}
}, 500);
}
function ClearIntv() {
clearInterval(intv);
}
Activates the counter on MouseOver, and cancels on MouseOut

Categories