Stop timer in jQuery and JS - javascript

I need to stop timer when popup is active.
I have two popups where it works. But it doesn't work with first one which is automatic when the page is on.
// Calling function - this is in popup.html
var popUp1 = false;
var popUp2 = false;
// Calling function with instruction by click
function togglePopup(){
popUp1 = document.getElementById("popup-1").classList.toggle("active");
timeToggle()
}
// Calling function with description by click
function myFunction(){
popUp2 = document.getElementById("desc").classList.toggle("activeD");
timeToggle()
}
// function for pausing game when there is popUp
function timeToggle(){
if (!popUp1 && !popUp2){
Init();
}else{
clearInterval(moveItIntervalID); //stopping time and random images
clearInterval(timeIntervalID);
}
}
//here is funcion with automatic popup
$( document ).ready(function() {
$('#descS').bPopup();
timeToggle()
(function(c){c.fn.bPopup=function(A,E){function L(){a.contentContainer=c(a.contentContainer||b);switch(a.content){case "iframe":var d=c('<iframe class="b-iframe" '+a.iframeAttr+"></iframe>");d.appendTo(a.contentContainer);t=b.outerHeight(!0);u=b.outerWidth(!0);B();d.attr("src",a.loadUrl);l(a.loadCallback);break;case "image":B();c("<img />").load(function(){l(a.loadCallback);F(c(this))}).attr("src",a.loadUrl).hide().appendTo(a.contentContainer);break;default:B(),c('<div class="b-ajax-wrapper"></div>').load(a.loadUrl,a.loadData,function(d,b,e){l(a.loadCallback,b);F(c(this))}).hide().appendTo(a.contentContainer)}}function B(){a.modal&&c('<div class="b-modal '+e+'"></div>').css({backgroundColor:a.modalColor,position:"fixed",top:0,right:0,bottom:0,left:0,opacity:0,zIndex:a.zIndex+v}).appendTo(a.appendTo).fadeTo(a.speed,a.opacity);C();b.data("bPopup",a).data("id",e).css({left:"slideIn"==a.transition||"slideBack"==a.transition?"slideBack"==a.transition?f.scrollLeft()+w:-1*(x+u):m(!(!a.follow[0]&&n||g)),position:a.positionStyle||"absolute",top:"slideDown"==a.transition||"slideUp"==a.transition?"slideUp"==a.transition?f.scrollTop()+y:z+-1*t:p(!(!a.follow[1]&&q||g)),"z-index":a.zIndex+v+1}).each(function(){a.appending&&c(this).appendTo(a.appendTo)});G(!0)}function r(){a.modal&&c(".b-modal."+b.data("id")).fadeTo(a.speed,0,function(){c(this).remove()});a.scrollBar||c("html").css("overflow","auto");c(".b-modal."+e).unbind("click");f.unbind("keydown."+e);k.unbind("."+e).data("bPopup",0<k.data("bPopup")-1?k.data("bPopup")-1:null);b.undelegate(".bClose, ."+a.closeClass,"click."+e,r).data("bPopup",null);clearTimeout(H);G();return!1}function I(d){y=k.height();w=k.width();h=D();if(h.x||h.y)clearTimeout(J),J=setTimeout(function(){C();d=d||a.followSpeed;var e={};h.x&&(e.left=a.follow[0]?m(!0):"auto");h.y&&(e.top=a.follow[1]?p(!0):"auto");b.dequeue().each(function(){g?c(this).css({left:x,top:z}):c(this).animate(e,d,a.followEasing)})},50)}function F(d){var c=d.width(),e=d.height(),f={};a.contentContainer.css({height:e,width:c});e>=b.height()&&(f.height=b.height());c>=b.width()&&(f.width=b.width());t=b.outerHeight(!0);u=b.outerWidth(!0);C();a.contentContainer.css({height:"auto",width:"auto"});f.left=m(!(!a.follow[0]&&n||g));f.top=p(!(!a.follow[1]&&q||g));b.animate(f,250,function(){d.show();h=D()})}function M(){k.data("bPopup",v);b.delegate(".bClose, ."+a.closeClass,"click."+e,r);a.modalClose&&c(".b-modal."+e).css("cursor","pointer").bind("click",r);N||!a.follow[0]&&!a.follow[1]||k.bind("scroll."+e,function(){if(h.x||h.y){var d={};h.x&&(d.left=a.follow[0]?m(!g):"auto");h.y&&(d.top=a.follow[1]?p(!g):"auto");b.dequeue().animate(d,a.followSpeed,a.followEasing)}}).bind("resize."+e,function(){I()});a.escClose&&f.bind("keydown."+e,function(a){27==a.which&&r()})}function G(d){function c(e){b.css({display:"block",opacity:1}).animate(e,a.speed,a.easing,function(){K(d)})}switch(d?a.transition:a.transitionClose||a.transition){case "slideIn":c({left:d?m(!(!a.follow[0]&&n||g)):f.scrollLeft()-(u||b.outerWidth(!0))-200});break;case "slideBack":c({left:d?m(!(!a.follow[0]&&n||g)):f.scrollLeft()+w+200});break;case "slideDown":c({top:d?p(!(!a.follow[1]&&q||g)):f.scrollTop()-(t||b.outerHeight(!0))-200});break;case "slideUp":c({top:d?p(!(!a.follow[1]&&q||g)):f.scrollTop()+y+200});break;default:b.stop().fadeTo(a.speed,d?1:0,function(){K(d)})}}function K(d){d?(M(),l(E),a.autoClose&&(H=setTimeout(r,a.autoClose))):(b.hide(),l(a.onClose),a.loadUrl&&(a.contentContainer.empty(),b.css({height:"auto",width:"auto"})))}function m(a){return a?x+f.scrollLeft():x}function p(a){return a?z+f.scrollTop():z}function l(a,e){c.isFunction(a)&&a.call(b,e)}function C(){z=q?a.position[1]:Math.max(0,(y-b.outerHeight(!0))/2-a.amsl);x=n?a.position[0]:(w-b.outerWidth(!0))/2;h=D()}function D(){return{x:w>b.outerWidth(!0),y:y>b.outerHeight(!0)}}c.isFunction(A)&&(E=A,A=null);var a=c.extend({},c.fn.bPopup.defaults,A);a.scrollBar||c("html").css("overflow","hidden");var b=this,f=c(document),k=c(window),y=k.height(),w=k.width(),N=/OS 6(_\d)+/i.test(navigator.userAgent),v=0,e,h,q,n,g,z,x,t,u,J,H;b.close=function(){r()};b.reposition=function(a){I(a)};return b.each(function(){c(this).data("bPopup")||(l(a.onOpen),v=(k.data("bPopup")||0)+1,e="__b-popup"+v+"__",q="auto"!==a.position[1],n="auto"!==a.position[0],g="fixed"===a.positionStyle,t=b.outerHeight(!0),u=b.outerWidth(!0),a.loadUrl?L():B())})};c.fn.bPopup.defaults={amsl:50,appending:!0,appendTo:"body",autoClose:!1,closeClass:"b-close",content:"ajax",contentContainer:!1,easing:"swing",escClose:!0,follow:[!0,!0],followEasing:"swing",followSpeed:500,iframeAttr:'scrolling="no" frameborder="0"',loadCallback:!1,loadData:!1,loadUrl:!1,modal:!0,modalClose:!0,modalColor:"#000",onClose:!1,onOpen:!1,opacity:.7,position:["auto","auto"],positionStyle:"absolute",scrollBar:!0,speed:250,transition:"fadeIn",transitionClose:!1,zIndex:9997}})(jQuery);
function Init(){
//set interval of moving image in case the user will not click it
moveItIntervalID = setInterval(moveIt, intervalTimeout);
timeIntervalID = setInterval(countDown, 1000);```

Related

How to make a toggle variable persist?

I'm working on a quiz page where I have a timer that I would like to be able to toggle on or off so it doesn't distract the user, and save the setting after submitting an answer. The timer function works, and calls on localStorage.getItem(). But when I try the below with a boolean to see if the showHideTimer() button is clicked, the timer always shows up when the next question appears. The console always logs true when the page loads a new question.
<script>
var clickCookie = 'clicked';
var clicked = localStorage.getItem(clickCookie);
console.log(clicked);
function showHideTimer(){
if(clicked==true){
document.getElementById("testHeaderRight").style.color = "black";
clicked=false;
localStorage.setItem(clickCookie, clicked);
console.log(clicked);
return clicked;
}
else{
document.getElementById("testHeaderRight").style.color = "white";
clicked=true;
localStorage.setItem(clickCookie, clicked);
console.log(clicked);
return clicked;
}
};
window.onload = function(){
if(clicked===null){
localStorage.setItem(clickCookie, false);
} else {
showHideTimer(clickCookie);
}
};
</script>
<body>
<button id="showHideTimer" onclick="showHideTimer()">Toggle Timer</button>
<div id="testHeaderRight">
Time Remaining :
<span id="time"></span>
</div>
<script>
var cookieName = 'startTimer';
var savedSeconds = localStorage.getItem(cookieName);
function startTimer(duration, display) {
var timer = duration, seconds;
setInterval(function () {
seconds = parseInt(timer);
display.textContent = secondsToHms(seconds);
var runningTime = (parseInt(seconds));
localStorage.setItem(cookieName, runningTime);
}, 1000);
}
window.onload = function () {
var startTime = 7200,
display = document.querySelector('#time');
if (savedSeconds === null){
startTimer(startTime, display);
} else {
startTimer(savedSeconds, display);
}
};
</script>
</body>
I've tried moving the window.onload call into the same function as the timer since that is functioning properly, but seems to make no difference. I've tried switching the clicked=true/false; variables around to make sure I'm not confusing myself with booleans, and they switch freely in the console when clicking on the button. I've tried changing the return value of the showHideTimer() function to be localStorage.setItem(clickCookie, clicked);
When you get the item out of storage it's a string, "true", not a boolean.
So your if(clicked==true) comparison never passes and you end up on the "false" path every time.

fail to create function interval to prevent other function run

hello i try to create the function to prevent the other function to run for 10 minutes IF user close the content and refresh the page.
the other function is to show the content when we scroll with 2 argument
first: it will run the function with first argument with no interval, if user click close and refresh. it will run the second argument that give interval
heres my code.
https://jsfiddle.net/8c1ng49a/1/
please look this code
var popUp= document.getElementById("popup");
var closePopUp= document.getElementsByClassName('popup-close');
var halfScreen= document.body.offsetHeight/2;
var showOnce = true;
var delay;
function slideUp(){
popUp.style.maxHeight="400px";
popUp.style.padding="10px 20px";
popUp.style.opacity="1";
if(popUp.className==="closed"){
popUp.className="";
}
}
function slideDown(){
popUp.style.maxHeight="0";
popUp.style.padding="0 20px";
popUp.style.opacity="0";
// add class closed for cache
if(popUp.className===""){
popUp.className="closed";
localStorage.setItem('closed', 'true'); //store state in localStorage
}
}
// start interval
function startDelay() {
delay = setInterval(slideUp, 1000);
}
// clear interval
function clearDelay() {
window.clearTimeout(delay);
}
// check if cache heve class close
window.onload = function() {
var closed = localStorage.getItem('closed');
if(closed === 'true'){
popUp.className="closed";
}
}
// show popup when scroll 50%
window.onscroll = function scroll(ev) {
// first time visited
if ((window.innerHeight+window.scrollY) >= halfScreen && showOnce) {
slideUp();
showOnce = false;
}
//same user mutilple time visited the site
else if((popUp.className==="closed" && window.innerHeight+window.scrollY) >= halfScreen && showOnce ){
startDelay();
showOnce = false;
}
};
// close button when click close
for(var i = 0; i<closePopUp.length; i++){
closePopUp[i].addEventListener('click', function(event) {
slideDown();
});
}
my interval didnt work onthe second argument its fire when i refresh, i dont know why.
but if add startDelay on my first arguments its work. but i need to place the interval on my second argu
When you want to make delay use setTimeout function.
Here is documentation of this function.
setInterval Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

Issues with resetting an interval

I have two elements. When I click the left element I want to change the right element into another element. If the left element is not clicked again the right element changes back to its original state. I've been able to make that happen, but I want to be able to click on that element again and have the interval I set restart. I feel like I'm close.
var changeImage = function(){
if(imageClicked == true){
var Img = document.getElementById('Img');
Img.setAttribute('src', "./images/img2.jpg");
imageTimeout = setTimeout(function(){
var Image = document.getElementById('Image');
Image.setAttribute('src', './images/image.jpg');
}, 3000)
imageClicked = false;
return imageTimeout;
} else {
imageClicked = true;
resetTimer();
}
}
var resetTimer = function(){
clearTimeout(imageTimeout);
window.setTimeout(imageTimeout, 3000);
}
random_image.addEventListener("click", changeImage, false);
The problem is that you are calling setTimeout(function ,delay) without a callback function.
The issue is in this line in the else block:
window.setTimeout(imageTimeout, 3000);
where imageTimeout is not a function, but the id of the timeout.
You need to create a separate function (let's call it timeoutFunction for example) with the timeout code and call it every time you invoke setTimeout.
After you create that function, and call it in the if block as well, change that line to:
imageTimeout = window.setTimeout(timeoutFunction, 3000);
from your code:
function timeoutFunction(){
var flowerImage = document.getElementById('flowerP');
flowerImage.setAttribute('src', './images/flowers.jpg');
}
by the way, you can define that flowerImage variable outside that function once instead of searching the DOM every time.
In order to clear a timeout, you need to call the clearTimeout function with the reference to the object that was returned by window.setTimeout. So you need to change your code to:
var resetTimer = function() {
clearTimeout(timeoutId);
createjs.Sound.stop(playSoundD);
timeoutId = window.setTimeout(imagetimeout, 3000);
console.log("I've been reset");
}

How does setInterval() work with button.onclick

I want the alertMe function to be called only when the button is clicked, but it gets called (the setInterval gets called which calls that) AS SOON AS THE PAGE LOADS. But if I take the pageLoad function away, then startButton is null and I can't do anything with it.Thanks in advance, guys!
/when user clicks start, start the animation
window.onload = pageLoad;
function pageLoad() {
var startButton = document.getElementById("start");
startButton.onclick = setInterval(alertMe,200);
}
function alertMe() {
alert("hi");
}
function pageLoad() {
var startButton = document.getElementById("start");
startButton.onclick = alertMe;
}
function alertMe() {
setInterval(function(){
alert("hi");
},200);
}
Move your interval inside the alertMe function, and pass that as a reference to startButton.onclick
DEMO: http://jsfiddle.net/gHS4a/
basically you need to do it like this:
startButton.onclick = function() {
interval = setInterval(alertMe, 200);
}
what it does is it sends reference to the alertMe function
another way would be:
startButton.onclick = function() {
interval = setInterval(function(){
alertMe();
}, 200);
}
which would send a reference to an anonymous function which will call the alertMe function

When timer reaches 0 click automatically on the button with Greasemonkey

Here is an example of a timer http://www.prezzipazzi.com/prodotto.php?id=1809
and I need a code that when the timer reaches 0 it click automatically on the button1809.
I tried this but it does not work:
var waitForZeroInterval = setInterval (CheckForZero, 0);
var hasRun = false;
function CheckForZero () {
if ( (unsafeWindow.seconds == 0) && (unsafeWindow.milisec == 0) )
{
clearInterval (waitForZeroInterval);
var targButton = document.getElementById ('bottone1809');
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
targButton.dispatchEvent (clickEvent);
};
if (!hasRun) {
hasRun = true;
setInterval(CheckForZero, 35000);
};
}
Does it click the button one time and then stop, or not click the button at all?
It looks like the hasRun logic is wrong.
I can't test at that site since (1) it annoys me greatly, (2) It seems to require a registration -- which I will not do. So, please confirm that it operates like this:
You login and load an auction page -- 1809 in this example.
The 30-second timer starts. When it hits 0, you click.
The timer resets -- Is there a delay? -- to a new 30-second countdown but the auction remains the same.
Repeat, ad nauseam.
If all that is true, and the current code clicked the button once, then this should work:
var waitForZeroInterval = null;
function RestartZeroCheck () {
waitForZeroInterval = setInterval (CheckForZero, 100);
}
function CheckForZero () {
if ( (unsafeWindow.seconds == 0) && (unsafeWindow.milisec == 0) )
{
clearInterval (waitForZeroInterval);
var targButton = document.getElementById ('bottone1809');
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
targButton.dispatchEvent (clickEvent);
//--- After a short pause, start checking for the next timer to zero.
setTimeout (RestartZeroCheck, 333);
};
}
RestartZeroCheck ();
Note that if that works, then examining the page's structure suggests that this:
var targButton = document.getElementById ('bottone1809');
Can be changed to this:
var targButton = document.querySelector (
"#left-inside div.post-wrapper td center input[id^='bottone']"
);
So that the auction number does not have to be hard-coded.
some more update:
HTML
<input type="button" name="button1" id="button1" onclick="do_some();"/>
script
var waitForZeroInterval = setInterval (function(){}, 0);
var hasRun = false;
function CheckForZero () {
clearInterval (waitForZeroInterval);
jQuery('#button1').click();
}
if (!hasRun) {
hasRun = true;
waitForZeroInterval = setInterval(CheckForZero(), 1000);
}
function do_some(){
alert("thank you");
}
This is working fine.. i have tested. i am getting that alert after 1 sec. The button is clicked and then the do_some function is called to display alert.
You can check here run code

Categories

Resources