during scroll call a function only once - javascript

I have a counter on a page. When I scroll to it I need start it only once. but now it starts twice during next scroll. Thank's.
var quit = false;
$(window).scroll(function() {
// ...
something();
function something() {
if (quit == true) {
return;
}
quit = true;
setTimeout(function() {
$(begin).html(2002);
}, 500); // this function must be call only once
}
}
}

$(document).on('scroll', function() {
something();
$(document).off('scroll');
});

this solution helped me https://github.com/HubSpot/odometer/issues/35
my second mistake was creating "new odometer" object

Related

Stop a recursive function

I am completely new in javascript and jquery... I have searched but can not find an answer to my problem...
I need to stop a function that call itself at the end (I read that this is called recursive function)
So my html
<div id="slide_show"></div>
Stop
My js
//call effect on load
$(function() {
moveSlide(true);
});
//move the div
function moveSlide(repeat) {
if(repeat === true) {
$('#slide_show').slideToggle('slow',function() {
setTimeout(function() {
moveSlide(true);
},2000);
});
} else {
return;
}
}
//stop the function
$(document).on('click','.stop',function(e) {
e.preventDefault();
moveSlide(false);
});
The function is called forever but I want to stop the function of being repeated when I click the button
What am I doing wrong?
Try with: clearTimeout() in else condition .
You need to create the setTimeout() in one variable.Then apply the clearTimout() if the condition is false(Its means a else statement)
var timer;
//call effect on load
$(function() {
moveSlide(true);
});
//move the div
function moveSlide(repeat) {
if(repeat === true) {
console.log('running')
$('#slide_show').slideToggle('slow',function() {
timer = setTimeout(function() {
moveSlide(true);
},2000);
});
} else {
clearTimeout(timer);
console.log('stopped')
return;
}
}
//stop the function
$(document).on('click','.stop',function(e) {
e.preventDefault();
moveSlide(false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="slide_show"></div>
Stop
I see that you are calling ever time at the method moveSlide, into the setTimeout
$('#slide_show').slideToggle('slow',function() {
setTimeout(function() {
**///moveSlide(true); ///here , will be calling recursive untill end**
},2000);
});
Test and tell us, if will help it
tks

custom when statement not firing functions

I am trying to make a when statement but it is not working as planned. Basically its a function to call another function when try. First before I explain further here is the syntax
when(function() {
//code here
});
Now basically... Think this way.. We have a progressbar.. We also have a custom event such as...
var pBarEvent = document.createEvent('Event');
pBarEvent.initEvent('pbardone', true, true);
document.addEventListener('pbardone', function() {
//code here
});
//if progress bar reaches 100 dispatchEvent
if (document.querySelector(".progress-bar").style.width === 100 + "%")
{
document.dispatchEvent(pBarEvent);
}
Now that piece of code is an example. If the document loads and its for instance at 50% it wont trigger until you add another event such as keydown or click. I dont want to do that I want to do.... "when" progress bar width equals 100% trigger it. Thats basically what needs to happen. So here is the code for the when statement so far (keep in mind its not the best looking one. As I dont normally do this but I wanted to keep this dynamic and who knows someone who later wants to do this can look at this question)
when function
function when(func)
{
var nowActive = false;
if (!typeof func === 'undefined')
{
func = new Function();
}
if (func)
{
nowActive = true;
clearInterval(whenStatementTimer);
}
else
{
nowActive = false;
var whenStatementTimer = setInterval(function() {
switch(func)
{
case true:
{
nowActive = true;
when();
break;
}
case false:
{
nowActive = false;
when();
break;
}
}
}, 1000);
}
if (nowActive === true)
{
func();
}
}
Now this does not work when I go to try something like....
when(function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("100%");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style("body", "background", "black");
});
});
It does not trigger. I need help possibly getting this when statement to work. What am I doing wrong? What can I do to fix it? No errors get thrown but it never fires.
edit based on answer
Function tried
function when(currentValue)
{
try
{
var o = {};
o.currentValue = currentValue;
o.do = function(func)
{
if (!typeof func === 'undefined')
{
func = new Function();
}
if (this.currentValue)
{
func();
}
else
{
setTimeout(this.do(func), 100);
}
};
return o;
}
catch(e)
{
console.log(e);
}
}
used as
when(true).do(function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("This divs going through changes!!");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style(".div", "background", "black");
});
});
This does not work. It never fires. But if I use a onclick listener as such it fires
document.addEventListener("click", function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("This divs going through changes!!");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style(".div", "background", "black");
});
}, false);
function when(statement){
o={};
o.statement=statement;
o.do=function(func){
awhen(this.statement,func);
};
return o;
}
function awhen(statement,func){
if(eval(statement)){
func();
}else{
window.setTimeout(function(){awhen(statement,func);},100);
}
}
Use:
when("true").do(function(){});
It works now :) . Its important to put the condition in ""!

Detect Mousemovent inside of blur function Jquery

I am trying to create a neat way to stop an AJAX called based upon if the browser is in focus, and if the mouse moves.. So here's what I want it to do:
If the user goes to a different tab in their browser, minimized the window, or goes somewhere else other than the web app, I want it to kill the AJAX calls in 1 minute. If the user moves the mouse anywhere in the web app, it should consider the user "focused" on the app, and thus continue the ajax calls. I put a timeout called "st" in there to take care of the "timeout" portion, but adding in a mouse detector is a little more advanced. Here's what I have:
var window_focus = true;
$(document).ready(function () {
$('#alertbox').click(function () {
$('#alertbox').slideUp("slow");
});
// Check focal point
$(window).focus(function () {
if (window_focus) {
return
}
window_focus = true;
waitForMsg();
}).blur(function () {
if (!window_focus) {
return
}
console.log('Init Suspension...');
// Set Timeout
$(function () {
st = setTimeout(function () {
clearTimeout(setTimeoutConst);
window_focus = false;
document.title = 'Timed Out | WEBSITE';
console.log('Suspended');
}, 60000);
});
});
waitForMsg();
});
I was going to try adding in something like this:
$(function () {
$().mousemove(function () {
console.log('Reinitialize');
clearTimeout(st);
waitForMsg();
});
});
But it didn't work. Thanks for your help.
http://jsfiddle.net/popnoodles/5mqMm/
You probably want this using .one(). This will see the mouse move, run your procedure and not run it again, until the window is reloaded or it's on another page.
Putting it inside of blur means blurring sets it up again.
}).blur(function () {
$(document).one('mousemove', function(){
// i react ONCE to the mouse being moved
console.log('Reinitialize');
clearTimeout(st);
waitForMsg();
// focus the window again as desired
$(window).trigger('focus');
});
if (!window_focus) {
return
}
console.log('Init Suspension...');
// Set Timeout
$(function () {
st = setTimeout(function () {
clearTimeout(setTimeoutConst);
window_focus = false;
document.title = 'Timed Out | WEBSITE';
console.log('Suspended');
}, 60000);
});
});
Try this jsfiddle
var window_focus = true, lastMouseMoveTime;
$(document).ready(function () {
lastMouseMoveTime = new Date().getTime();
$('#alertbox').click(function () {
$('#alertbox').slideUp("slow");
});
// Check focal point
$(window).focus(function () {
if (window_focus) {
return
}
window_focus = true;
waitForMsg();
}).blur(function () {
if (!window_focus) {
return
}
window_focus = false;
console.log('Init Suspension...');
// Set Timeout
});
waitForMsg();
$(document).mousemove(function(){
lastMouseMoveTime = new Date().getTime();
if(!window_focus ){
waitForMsg(); // restarting ajax if it stopped because of mousemove.
}
});
});
in your ajax call method
if( !window_focus){
if( new Date().getTime() - lastMouseMoveTime > 60*1000 ){
return;
}
}

Repeat code every x seconds but not if [insert check here]

This is a followup to this question, where I found out how to make code be repeated every x seconds. Is it possible to make an event that can change this? I.e. I have a checkbox which is meant to control whether this is repeated or not, so I figured I'd need something like this:
$(checkbox).bind("change", function() {
switch(whether if it is ticked or not) {
case [ticked]:
// Make the code repeat, while preserving the ability to stop it repeating
case [unticked]:
// Make the code stop repeating, while preserving the ability to start again
}
});
I have no idea what I could put in the cases.
You can do it by assigning your setInterval function to a variable.
var interval = setInterval(function() { }, 1000);
and then you can stop setInterval by
clearInterval(interval);
p.s.
to start your interval you need to call var interval = setInterval(function() { }, 1000); again
You can either stop and start the interval:
var timer;
function start() {
timer = window.setInterval(function(){
// do something
}, 1000);
}
function stop() {
window.clearInterval(timer);
}
start();
$(checkbox).bind("change", function() {
if ($(this).is(':checked')) {
start();
} else {
stop();
}
});
Or you can have a flag causing the interval to skip the code:
var enabled = true;
var timer = window.setInterval(function(){
if (!enabled) {
// do something
}
}, 1000);
$(checkbox).bind("change", function() {
enabled = $(this).is(':checked');
});
function fooFunc() {
$('#foo').text(+new Date());
}
var id;
var shouldBeStopped = false;
$('input').change(function() {
if (shouldBeStopped)
clearInterval(id);
else
id = setInterval(fooFunc, 200);
shouldBeStopped = !shouldBeStopped;
});​
Live DEMO

execute javascript after focused on an element

I need to run execFunc(); not only when the user moves onto the next field, but also runs when the user remains focused on the same field for 5 seconds.
$('input[name="email"]').bind('blur', function () {
execFunc();
});
var timer = null;
$('input[name="email"]').blur(function(e){
if (timer) clearTimeout(timer);
execFunc();
}).focus(function(e){
timer = setTimeout(execFunc, 5000);
});
If you're doing form validation, there are better ways of doing this.
How about...
$('input[name="email"]').bind('blur', execFunc).bind('focus', function() {
setTimeout(execFunc, 5000);
});
If the function isn't idempotent and you must execute it only once, you can do:
var execFuncHasExecuted = false;
function execFunc() {
if (execFuncHasExecuted)
return false;
execFuncHasExecuted = true;
// ... remainder of implementation
}
This should suffice
var g_timeout = null;
$('input[name="email"]')
.blur(function () {
execFunc();
})
.focus(function(){
if (g_timeout) clearTimeout(g_timeout);
g_timeout= setTimeout(execFunc, 5000);
});

Categories