To blur the keyboard on mobile devices, I use an interval with count on the showPicker() function.
showPicker = function () {
var timesRun = 0;
var intervalblur = setInterval(function () {
timesRun += 1;
if (timesRun === 60) {
clearInterval(intervalblur);
}
console.log('fire blur');
editorInstance.blur();
}, 600);
};
When the picker is closed, I want to clear the interval. I did on this function:
hidePicker = function () {
clearInterval(intervalblur);
}
But I am getting this error:
Uncaught ReferenceError: intervalblur is not defined
Any ideas? Thank you
Because it's not defined in a global scope but in showPicker function's scope.
You have 3 options
Define it globally
var intervalblur;
showPicker = function () {
var timesRun = 0;
intervalblur = setInterval(function () {
timesRun += 1;
if (timesRun === 60) {
clearInterval(intervalblur);
}
console.log('fire blur');
editorInstance.blur();
}, 600);
};
clearInterval(intervalblur);
Define it on window
showPicker = function () {
var timesRun = 0;
window.intervalblur = setInterval(function () {
timesRun += 1;
if (timesRun === 60) {
clearInterval(intervalblur);
}
console.log('fire blur');
editorInstance.blur();
}, 600);
};
clearInterval(intervalblur);
showPicker will return the intervalId
showPicker = function () {
var timesRun = 0;
var intervalblur = setInterval(function () {
timesRun += 1;
if (timesRun === 60) {
clearInterval(intervalblur);
}
console.log('fire blur');
editorInstance.blur();
}, 600);
return intervalblur;
};
var intervalId = showPicker();
clearInterval(intervalId);
Personally I'd prefer option 3 because I don't like global variables.
Related
I need to exit from a running interval if the conditions are correct:
var refreshId = setInterval(function() {
var properID = CheckReload();
if (properID > 0) {
<--- exit from the loop--->
}
}, 10000);
Use clearInterval:
var refreshId = setInterval(function() {
var properID = CheckReload();
if (properID > 0) {
clearInterval(refreshId);
}
}, 10000);
Pass the value of setInterval to clearInterval.
const interval = setInterval(() => {
clearInterval(interval);
}, 1000)
Demo
The timer is decremented every second, until reaching 0.
let secondsRemaining = 10
const interval = setInterval(() => {
// just for presentation
document.querySelector('p').innerHTML = secondsRemaining
// time is up
if (secondsRemaining === 0) {
clearInterval(interval);
}
secondsRemaining--;
}, 1000);
<p></p>
Updated for ES6
You can scope the variable to avoid polluting the namespace:
const CheckReload = (() => {
let counter = - 5;
return () => {
counter++;
return counter;
};
})();
{
const refreshId = setInterval(
() => {
const properID = CheckReload();
console.log(properID);
if (properID > 0) {
clearInterval(refreshId);
}
},
100
);
}
I have this code to start a setTimeout function with a button and to stop it with another button, but if I stop it and start it, it will start over, Is there any way to get a pause/continue button?
Javascript code:
var timeout1, timeout2, timeout3;
function timedText() {
timeout1 = setTimeout(desertAK, 1000)
timeout2 = setTimeout(fourAlarmShotgun, 5000)
timeout3 = setTimeout(frostbiteAR, 9000)
}
function stopTimeout() {
clearTimeout(timeout1);
clearTimeout(timeout2);
clearTimeout(timeout3);
}
function desertAK() {
document.getElementById("leser").innerHTML = '<iframe src="https://opskins.com/?loc=shop_search&sort=lh&app=433850_1&search_item=%22Desert%20Warfare%20AK-47%22"></iframe>';
}
function fourAlarmShotgun() {
document.getElementById("leser2").innerHTML = '<iframe src="https://opskins.com/?loc=shop_search&sort=lh&app=433850_1&search_item=%22Four%20Alarm%2012GA%20Pump%20Shotgun%22"></iframe>';
}
function frostbiteAR() {
document.getElementById("leser").innerHTML = '<iframe src="https://opskins.com/?loc=shop_search&sort=lh&app=433850_1&search_item=%22Frostbite%20AR-15%22"></iframe>';
}
HTML buttons:
<button onclick="timedText()">Start</button>
<button onclick="stopTimeout()">Stop</button>
var Timer = (function () {
var isExeced = [1,1,1];
var timeout1, timeout2, timeout3;
var startTime, costTime = 0;
var finished = false;
var status = 0;
function reset () {
costTime = 0;
status = 0;
finished = false;
isExeced = [1,1,1];
}
function desertAK () {
document.getElementById("leser").innerHTML = '<iframe src="https://opskins.com/?loc=shop_search&sort=lh&app=433850_1&search_item=%22Desert%20Warfare%20AK-47%22"></iframe>';
}
function fourAlarmShotgun () {
document.getElementById("leser2").innerHTML = '<iframe src="https://opskins.com/?loc=shop_search&sort=lh&app=433850_1&search_item=%22Four%20Alarm%2012GA%20Pump%20Shotgun%22"></iframe>';
}
function frostbiteAR () {
document.getElementById("leser").innerHTML = '<iframe src="https://opskins.com/?loc=shop_search&sort=lh&app=433850_1&search_item=%22Frostbite%20AR-15%22"></iframe>';
}
function timedText () {
if (finished) {
return resume();
}
if (status === 1) {
return;
} else {
status = 1;
}
startTime = +new Date();
if (isExeced[0]) {
timeout1 = setTimeout(function () {
isExeced[0] = 0;
desertAK();
}, 1000 - costTime);
}
if (isExeced[1]) {
timeout2 = setTimeout(function () {
isExeced[1] = 0;
fourAlarmShotgun();
}, 5000 - costTime);
}
if (isExeced[2]) {
timeout3 = setTimeout(function () {
isExeced[2] = 0;
finished = true;
status = 0;
frostbiteAR();
}, 9000 - costTime);
}
}
function stopTimeout () {
costTime += +new Date() - startTime;
status = 0;
clearTimeout(timeout1);
clearTimeout(timeout2);
clearTimeout(timeout3);
}
function resume () {
stopTimeout();
reset();
timedText();
}
return {
start: timedText,
stop: stopTimeout,
resume: resume
}
})();
Use like below:
<button onclick="Timer.start();">Start</button>
<button onclick="Timer.stop();">Stop</button>
Add breakpoint variable status which save last doing operation
var timeout1, timeout2, timeout3;
var status = 0;
function timedText() {
if(status + 1 == 1) {
timeout1 = setTimeout(desertAK, 1000)
timeout2 = setTimeout(fourAlarmShotgun, 5000)
timeout3 = setTimeout(frostbiteAR, 9000)
} else if(status == 2) {
timeout2 = setTimeout(fourAlarmShotgun, 5000)
timeout3 = setTimeout(frostbiteAR, 9000)
timeout1 = setTimeout(desertAK, 1000)
} else {
timeout3 = setTimeout(frostbiteAR, 9000)
timeout1 = setTimeout(desertAK, 1000)
timeout2 = setTimeout(fourAlarmShotgun, 5000)
}
}
function stopTimeout() {
clearTimeout(timeout1);
clearTimeout(timeout2);
clearTimeout(timeout3);
}
function desertAK() {
status = 0;
document.getElementById("leser").innerHTML = '<iframe src="https://opskins.com/?loc=shop_search&sort=lh&app=433850_1&search_item=%22Desert%20Warfare%20AK-47%22"></iframe>';
}
function fourAlarmShotgun() {
status = 1;
document.getElementById("leser2").innerHTML = '<iframe src="https://opskins.com/?loc=shop_search&sort=lh&app=433850_1&search_item=%22Four%20Alarm%2012GA%20Pump%20Shotgun%22"></iframe>';
}
function frostbiteAR() {
status = 2;
document.getElementById("leser").innerHTML = '<iframe src="https://opskins.com/?loc=shop_search&sort=lh&app=433850_1&search_item=%22Frostbite%20AR-15%22"></iframe>';
}
I wrote this code that starts a timer. I fire a function that restarts the timer when it reaches 0. It works, but I get an error in the console that says Uncaught TypeError: Cannot read property 'restartTimer' of undefined. It has to do with this.restartTimer();
timer = utility.math.surveyTimer({
seconds: time,
onUpdateStatus: function(remainingTime) {
$(surveyTimerNode).text(remainingTime);
},
restartTimer: function() {
window.TimerInterval = timer.start();
},
onCounterEnd: function() {
if (utility.bool.isQuestionScreen()) {
if (utility.bool.surveyWillLoop()) {
data.setPersistentSurveyData('DSM_SURVEY_SCREENS', surveyScreens);
data.setPersistentSurveyData('DSM_SURVEY_SCREEN_ORDER', surveyScreenOrder);
tagData = data.getPersistentSurveyData('DSM_SURVEY_DATA');
apiParam = api.helper.buildAPIParam('surveyTimeout', tagData);
api.post.postToAPI(apiParam);
parent.resetSurveyProgress();
parent.moveToNextScreen();
this.restartTimer();
} else {
parent.goToEndscreen();
}
}
}
});
window.TimerInterval = timer.start();
No errors in JSLint, just errors on run. What's so bizarre is that it works, the timer does reset. How do I remove this error?
Here's the function that actually does the timer counting:
this.surveyTimer = function (options) {
var timer,
instance = this,
minutes,
secondsMinusMinutes,
remainingTime,
seconds = options.seconds || 30,
updateStatus = options.onUpdateStatus || function () {
return undefined;
},
counterEnd = options.onCounterEnd || function () {
return undefined;
};
function zeroPad(n) {
return (n < 10) ? ("0" + n) : n;
}
function decrementCounter() {
minutes = Math.floor(seconds / 60);
secondsMinusMinutes = seconds - minutes * 60;
remainingTime = minutes + ':' + zeroPad(secondsMinusMinutes);
updateStatus(remainingTime);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds -= 1;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
return timer;
};
this.stop = function () {
clearInterval(timer);
};
return this;
};
Just a guess, but I think your use of this in your options object is not the this you think it is...
Try changing your implementation of surveyTimer, where it is currently:
counterEnd();
to:
counterEnd.call(options);
I'm creating a simple slideshow using jQuery and some javascript, but I'm running into issues using the setInterval functions.
JSFiddle of the Project
$(document).ready(function () {
slidePos = 1;
autoScrollInterval = setInterval(function () {
slidePos = SlideRight(slidePos)
}, 7000);
$(".ss-indicator-arrow").css("width", $(".ss-slideshow").width() / $(".ss-slide").length);
$(".ss-right-arrow").click(function () {
window.clearInterval(autoScrollInterval);
slidePos = SlideRight(slidePos);
setTimeout(function () {
autoScrollInterval = setInterval(function () {
slidePos = SlideRight(slidePos)
}, 7000);
}, 10000);
});
$(".ss-left-arrow").click(function () {
window.clearInterval($.autoScrollInterval);
slidePos = SlideLeft(slidePos);
setTimeout(function () {
autoScrollInterval = setInterval(function () {
slidePos = SlideRight(slidePos)
}, 7000);
}, 10000);
})
});
$(window).resize(function () {
$(".ss-indicator-arrow").css("width", $(".ss-slideshow").width() / $(".ss-slide").length);
Reset();
});
function SlideRight(slidePos) {
slidePos++;
if (slidePos <= $(".ss-slide").length) {
$(".ss-container").css("margin-left", -((slidePos - 1) * $(".ss-slideshow").width()) + "px");
$(".ss-indicator-arrow").css("left", ($(".ss-indicator-arrow").width() * (slidePos - 1) + "px"));
}
else
Reset();
return slidePos
}
function SlideLeft(slidePos) {
slidePos--;
if (slidePos > 0) {
$(".ss-container").css("margin-left", -((slidePos - 1) * $(".ss-slideshow").width()) + "px");
$(".ss-indicator-arrow").css("left", ($(".ss-indicator-arrow").width() * (slidePos - 1) + "px"));
}
else {
slidePos = $(".ss-slide").length;
$(".ss-container").css("margin-left", -((slidePos - 1) * $(".ss-slideshow").width()) + "px");
$(".ss-indicator-arrow").css("left", ($(".ss-indicator-arrow").width() * (slidePos - 1) + "px"));
}
return slidePos;
}
function Reset() {
slidePos = 1;
$(".ss-container").css("margin-left", "0px");
$(".ss-indicator-arrow").css("left", "0px");
}
So far I've tried many different methods, and have somewhat ruined the basic functionality I had before. But for now, the primary issue is that if an arrow is pressed multiple times, after the wait setTimeout period, it will then progress through the same number of slides (ie if the button is pressed 3 times, when the setInterval starts over it will move 3 slides again)
What is the most effective way I can have an interval that pauses after user input, then resumes again?
What is the most effective way I can have an interval that pauses
after user input, then resumes again?
Look at this example
DEMO: http://jsfiddle.net/n8c3pycw/1/
var Timer = {
totalSeconds: 300,
start: function () {
var self = this;
this.interval = setInterval(function () {
self.totalSeconds -= 1;
if (self.totalSeconds == 0) {
Timer.pause();
}
$("#timer").text(parseInt(self.totalSeconds, 10));
}, 1000);
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
if (!this.interval) this.start();
}
}
Timer.start();
$("#start").click(function(){
Timer.resume();
});
$("#stop").click(function(){
Timer.pause();
});
Try using either setTimeout or setInterval.
example: var autoScrollInterval = runInterval();
function tochangeyourimage (delta) {
autoRunInterval = runInterval();
};
function runInterval() {
return setInterval(tochangeyourimage, 7000, 1);
Below is some code that has no jquery, but it is not working:
function start() {
var img = 0,
pic = ['nature', 'grass', 'earth', 'fall2', 'waterfall'],
slider = document.getElementsByClassName('slide_img'),
timerID = 0,
delay = 4000;
function back() {
img--;
if (img <= 0) {
img = pic.length - 1;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
function go() {
img++;
if (img >= pic.length) {
img = 0;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
document.getElementById('back').onclick = function() {
back();
}
document.getElementById('go').onclick = function() {
go();
}
slider.onmouseenter = function() {
clearTimeout(timerID);
}
document.getElementById('go').onmouseenter = function() {
clearTimeout(timerID);
}
document.getElementById('back').onmouseenter = function() {
clearTimeout(timerID);
}
slider.onmouseleave = function() {
clearTimeout(timerID);
auto();
}
function auto() {
timerID = setTimeout(function () {
go();
auto();
}, delay);
}
auto();
}
Here is what it is in jquery, this one works:
$('document').ready(function() {
var img = 0,
pic = ['nature', 'grass', 'earth', 'fall2', 'waterfall'],
slider = $('img.slide_img'),
timerID = 0,
delay = 4000;
function back() {
img--;
if (img <= 0) {
img = pic.length - 1;
}
slider.attr('src', 'pictures/' + pic[img] + '.jpg');
}
function go() {
img++;
if (img >= pic.length) {
img = 0;
}
slider.attr('src', 'pictures/' + pic[img] + '.jpg');
}
$('button#back').on('click', function() {
back();
});
$('button#go').on('click', function() {
go();
});
$(slider).on('mouseenter', function () {
clearTimeout(timerID);
});
$('button#go').on('mouseenter', function () {
clearTimeout(timerID);
});
$('button#back').on('mouseenter', function () {
clearTimeout(timerID);
});
$(slider).on('mouseleave', function () {
clearTimeout(timerID);
auto();
});
function auto() {
timerID = setTimeout(function () {
go();
auto();
}, delay);
}
auto();
});
What am i doing wrong, why is the first one not working. Im am trying to get rid of jquery so i dont have to include the source file.
You are not executing onload
try
var img = 0,
pic = ['nature', 'grass', 'earth', 'fall2', 'waterfall'],
slider,
timerID = 0,
delay = 4000;
window.onload=function() {
slider = document.getElementsByClassName('slide_img');
document.getElementById('back').onclick = function() {
back();
}
document.getElementById('go').onclick = function() {
go();
}
slider.onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('go').onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('back').onmouseover = function() {
clearTimeout(timerID);
}
slider.onmouseout = function() {
clearTimeout(timerID);
auto();
}
auto();
}
function auto() {
timerID = setTimeout(function () {
go();
auto();
}, delay);
}
function back() {
img--;
if (img <= 0) {
img = pic.length - 1;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
function go() {
img++;
if (img >= pic.length) {
img = 0;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
Use "onmouseover" and onmouseout" for canonical events:
slider.onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('go').onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('back').onmouseover = function() {
clearTimeout(timerID);
}
slider.onmouseout = function() {
clearTimeout(timerID);
auto();
}
And don't forget to define "slider" (the initial part is missing in your script):
var slider = document.querySelector('img.slide_img');
<body onload="start"></body>
The JavaScript start doesn't do anything. If you want to call a function, then you need to follow it with ().
This is a rather obtrusive way to deal with event handler assignment though. It is generally preferred to assign such things with JavaScript:
addEventListener('load', start);
See MDN for compatibility notes.
However, you don't have anything in your code that depends on the entire document being loaded. So you can simply:
<script>
start();
</script>
</body>
at the end of your document.
(You can put the whole script there for that matter, and keep it in an external file).