So I am trying to run a pop up script using timer interval and for whatever reason the timer doesnt count it just fires on load.
idleTime = 0;
$(document).ready(function() {
$limit = 5;
if ($.cookie('newVisit') != '1') {
$.get('/pop_form.htm', function(data) {
$('.subs-popup').html(data);
});
function timerIncrement() {
idleTime++;
if (idleTime > $limit) {
$('.subs-popup ').show();
idleTime = 0;
}
}
var idleInterval = setInterval(timerIncrement, 1000); // 1 second
$(this).mousemove(function(e) {
idleTime = 0;
});
$(this).keypress(function(e) {
idleTime = 0;
});
$.cookie('newVisit', '1', {
expires: 364,
path: "/"
});
}
});
Just not really sure what else to do in order to get this to work correctly? Any help would be greatly appreciated.
Update***
So I did what you said and here is my code with the changes. Except now i am getting an unexpected token error.
var idleTime = 0;
$(document).ready(function() {
var limit = 7;
if ($.cookie('newVisit') !='1') {
$.get('/pop_form.htm', function(data) {
$('.subs-popup').html(data);
});
function timerIncrement() {
idleTime++;
if (idleTime > limit) {
$('.subs-popup ').show();
idleTime = 0;
}
}
var idleInterval = setInterval(timerIncrement, 1000); // 1 second
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
$.cookie('newVisit', '1', { expires: 364 , path: "/" });
}
}); <----- this is where i get the unexpected token error
Here's an alternative solution:
var timeout = null;
function resetTimer() {
clearTimeout(timeout)
timeout = setTimeout(function() {
clearTimeout(timeout)
alert("Idle!")
}, 5000);
}
$(document).mousemove(function(e) {
resetTimer();
});
$(document).keypress(function(e) {
resetTimer()
});
This uses the return value from setTimeout() which is a reference to the timeout. You can call clearTimeout() with this reference and it will cancel/clear/remove the timeout, so you can start a new one each time the mouse moves / a key is pressed - rather than keep a record of how many times it's been hit.
Fiddle: https://jsfiddle.net/2ewzr4sx/
Works for me.
Reduced test case:
var idleTime = 0;
$(document).ready(function() {
var limit = 5;
function timerIncrement() {
idleTime++;
if (idleTime > limit) {
alert('Idle!');
idleTime = 0;
}
}
var idleInterval = setInterval(timerIncrement, 1000); // 1 second
$(this).mousemove(function(e) {
idleTime = 0;
});
$(this).keypress(function(e) {
idleTime = 0;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
PS:
Make sure to declare all your variables with var.
You also should not let your variable begin with $ if they don't hold a jQuery-Object (e.g. $limit should be limit)
Note that
touch-device users wont move any mouse, thus "idle" every time.
Be aware that the interval set with setInterval() ist not guaranteed to be executed in exactly this time. E.g. browsers with throttle intervals when tab is in background.
After first run you won't see any popup this is because of the scope of the setInterval() when it runs 2nd time it runs function in window scope same you can see by
function timerIncrement() {
console.log('scope is:', this);
idleTime++;
/* rest your function code goes here... */
So to prevent it you have to define timerIncrement() in global scope so that setInterval can access and call it; :)
Updated code:
function timerIncrement() {
idleTime++;
if (idleTime > $limit) {
$('.subs-popup ').show();
idleTime = 0;
}
}
var idleTime = 0;
var idleInterval = 0;
var $limit = 5;
$(document).ready(function() {
if ($.cookie('newVisit') != '1') {
$.get('/pop_form.htm', function(data) {
$('.subs-popup').html(data);
});
idleInterval = setInterval(timerIncrement, 1000); // 1 second
$(this).mousemove(function(e) {
idleTime = 0;
});
$(this).keypress(function(e) {
idleTime = 0;
});
$.cookie('newVisit', '1', {
expires: 364,
path: "/"
});
}
});
Related
I'm getting error saying Uncaught TypeError: Cannot read properties of undefined (reading 'fireCustomEvent'). Please help how to resolve this as I'm making use of Oracle JET to write this javascript code
define([], () => {
'use strict';
//var eventHelper;
var idleTime = 0;
class PageModule {
constructor(context) {
this.eventHelper = context.getEventHelper();
// Increment the idle time counter every minute.
this.idleInterval = setInterval(this.timerIncrement, 5000); // 10 second
}
timerIncrement() {
console.log(idleTime);
idleTime = idleTime + 1;
if (idleTime > 0) {
console.log(this.eventHelper);
this.eventHelper.fireCustomEvent('openDialog', {});
}
}
}
// Zero the idle timer on mouse movement.
$(this).mousemove(function (e) { idleTime = 0; });
$(this).keypress(function (e) { idleTime = 0; });
return PageModule;
});
This issue may be related to Referencing "this" inside setInterval/setTimeout.
With the current code, after transpile, the PageModule will be
var PageModule = /** #class */ (function () {
function PageModule(context) {
//.....
this.idleInterval = setInterval(this.timerIncrement, 5000); // 10 second
}
PageModule.prototype.timerIncrement = function () {
if (idleTime > 0) {
console.log(this.eventHelper);
this.eventHelper.fireCustomEvent('openDialog', {});
}
};
return PageModule;
}());
this is not referring to PageModule but Window object of browser inside the timerIncrement function and because of that the eventHelper is undefined.
Solution 1: Use an arrow function.
const timerIncrement = () => {
//....
if (idleTime > 0) {
console.log(this.eventHelper);
this.eventHelper.fireCustomEvent('openDialog', {});
}
}
Solution 2:
Pass this to timerIncrement as given below and use as self inside the timerIncrement function.
constructor(context) {
this.idleInterval = setInterval(this.timerIncrement, 5000, this);
}
timerIncrement(self) {
//....
if (idleTime > 0) {
console.log(self.eventHelper);
self.eventHelper.fireCustomEvent('openDialog', {});
}
}
I got this code from: Jquery: mousedown effect (while left click is held down)
It is behaving that if I am holding the button in every 50ms it will do something.
var timeout = 0;
$('#button_add').mousedown(function () {
timeout = setInterval(function () {
value_of_something ++;
}, 50);
return false;
});
});
But what I want is to execute this part after holding down the button by 1 second and it will continuously do the action 50ms.
As I said you need to use setTimeout()
var timeout = 0;
$('#button_add').mousedown(function () {
setTimeout(function(){
timeout = setInterval(function () {
value_of_something ++;
}, 50);
} , 1000);
return false;
});
Jsfiddle
Please use this code... You have to clearTimeout when user mouseup :
var timeout = 0;
$('#button_add').mousedown(function() {
oneSecondTimer = setTimeout(function() {
timeout = setInterval(function() {
value_of_something++;
}, 50);
}, 1000);
return false;
});
$("#button_add").mouseup(function() {
clearTimeout(oneSecondTimer);
});
var startTimeout = function () {
setInterval(timerIncrement, 1000);
document.getElementsByTagName('body')[0].addEventListener('mousemove', function () { globals.idleTime = 0; });
document.getElementsByTagName('body')[0].addEventListener('keypress', function () { globals.idleTime = 0; });
};
var timerIncrement = function () {
Tools.getParameterFromDatabase('idleTime', function(idleTime) {
globals.idleTime++;
if (globals.idleTime > idleTime / 1000 - 1) {
doAction();
}
});
};
doAction() method should fire when user does nothing for idleTime seconds - this idleTime is places in the database, so I have to load it with ajax.
The problem is that globals.idleTime is not setting to 0 with user action. Events seem to fire only after doAction() is being called.
How can I solve this?
You can set idleTime to 0 manually.
I need my code to run x amount of times and then pause for 30 seconds or so before resuming. Any ideas?
myslidefunction();
var tid = setInterval(myslidefunction, 1000);
function myslidefunction() {
setTimeout(function () {
//do stuff
}, 400);
};
You can keep a run-count, and use normal_duration + 30000 as the setTimeout delay for the X+ 1st time.
var runCount = 0, runsBeforeDelay = 20;
function myslidefunction(){
// .. stuff
runCount++;
var delay = 0;
if(runCount > runsBeforeDelay) {
runCount = 0;
delay = 30000;
}
setTimeout(myslidefunction, 400 + delay);
};
// start it off
setTimeout(myslidefunction, 1000);
var counter = 0;
var mySlideFunction = function(){
/* your "do stuff" code here */
counter++;
if(counter>=10){
counter = 0;
setTimeout(mySlideFunction, 30000);
}else{
setTimeout(mySlideFunction, 1000);
}
}
mySlideFunction();
(function() {
var count = {
digit: 0,
increment: function() {
var interval = setInterval(function() {
if (++count.digit == 10) {
clearInterval(interval);
count.decrement();
}
var update = document.getElementById("liveUpdate");
update.innerHTML = count.digit;
}, 500);
},
decrement: function() {
var interval = setInterval(function() {
if (--count.digit == -1) {
clearInterval(interval);
}
}, 500);
}
};
count.increment();
})();
It stops but it doesn't go down? What could be the problem?
Your decrement function never updates the output anywhere. The variable is going down but you don't show that on screen.
Try (or check the corresponding JSFiddle):
(function() {
var update = document.getElementById("liveUpdate");
var count = {
digit: 0,
increment: function() {
var interval = setInterval(function() {
if (++count.digit == 10) {
clearInterval(interval);
count.decrement();
}
update.innerHTML = count.digit;
}, 500);
},
decrement: function() {
var interval = setInterval(function() {
if (--count.digit == -1) {
clearInterval(interval);
}
update.innerHTML = count.digit;
}, 500);
}
};
count.increment();
})();
setInterval will call the function every 500 seconds. It will not stop until you stop it. You can read more about stopping it at Stop setInterval call in JavaScript
It't not a bug, it's a feature ;-). setInterval() runs the given function in a loop with a given interval (500 ms). See this article for details.