How to pause a setTimeout function - javascript

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>';
}

Related

ClearInterval is not defined - jQuery

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.

Play an audio file in Javascript

I'm trying to play an audio file in js. what am i doing wrong?
The script auto-stops after some events which is working 100%, now all I want to do is add a sound after it stops
Here is the code in:
function stop() {
stop_flag = true;
var audio = new Audio('play.mp3');
audio.play();
}
Here is the complete script.js the function is at the bottom.
chrome.runtime.onMessage.addListener(function(message) {
if (message.action == "init") {
init(message.options.divider, message.options.delay, message.options.maxLosses);
}
if (message.action == "stop") {
stop();
}
});
var stop_flag;
function init(divider, delay, maxLosses) {
var $table = $('table.dice_table').last();
var lastBetNumber;
var lastBetValue;
var lastProfit;
var losses = 0;
stop_flag = false;
loop_start();
function loop_start() {
lastBetNumber = getLastBetNumber();
var betValue = (getCurrentBalance() / divider).toFixed(9);
//var betValue = (getCurrentBalance() / divider);
lastBetValue = betValue;
$("input.bet").val(betValue);
play();
setTimeout(loop, delay);
}
function loop() {
if (stop_flag)
return;
waitForTableChange()
.then(roll)
.catch(loop_start);
function roll() {
//only if the last bet has changed \/
lastBetNumber = getLastBetNumber();
lastProfit = $table.children('tbody').children('tr').first().children('td').last().text()[0];
changeBet();
if (losses >= maxLosses)
return;
play();
setTimeout(loop, delay);
}
}
function waitForTableChange() {
return new Promise(function(resolve, reject) {
var n = 0;
attempt();
function attempt() {
n++;
if (n >= 100) {
reject();
return;
}
if (getLastBetNumber() == lastBetNumber) {
setTimeout(attempt, 100);
return;
}
resolve();
}
});
}
function changeBet() {
var newBetValue;
if (lastProfit == "-") {
losses++;
newBetValue = lastBetValue * 2;
} else {
losses = 0;
newBetValue = (getCurrentBalance() / divider).toFixed(9);
}
lastBetValue = newBetValue;
$("input.bet").val(newBetValue);
}
function play() {
$('input.clDicePlay').first()[0].click();
}
function getLastBetNumber() {
return $table.children('tbody').children('tr').first().children('td').first().text();
}
function getCurrentBalance() {
return $('.dice_select .chosen-single span').text().split('- ')[1].split(' ')[0];
}
}
function stop() {
var audio = new Audio('play.mp3');
stop_flag = true;
audio.play();
}
The problem is you are setting audio within the function stop(), which makes it local to that function. Once a function has been executed, all local vars are destroyed. You need to use the global scope to keep the object alive.
For example:
// set 'audio' in the global scope
var audio = new Audio('/path/to/default.mp3');
// create a play / pause button
function playPause(e) {
// NOTE: audio is from the gloabl scope
if (this.textContent == 'Play') {
audio.play();
this.textContent = 'Pause';
} else {
audio.pause();
this.textContent = 'Play';
}
}
window.onload = function() {
var a = document.getElementById('func');
a.addEventListener('click',playPause,false);
}
<button id="func">Play</button>

Image slideshow timer speed getting increased when we click on next or previous buttons, using JavaScript

I have written simple image slider using JavaScript. In that I have set 5000 ms timer to slide automatically. but it is getting increased when we click on next or previous button. I have pasted the code below
HTML Code:
<section id="intro">
<div id="prev"><br/><br/><br/><br/><img onclick="rotateImages(0);" src="./images/slider/prev1.png"/></div>
<div id="next"><img onclick="rotateImages(1);" src="./images/slider/next1.png"/></div>
</section>
JavaScript Code:
<script type="text/javascript">
var num = 0;
var temp = 0;
var speed = 5000;
var preloads = [];
preload(
'1.png',
'2.jpg',
'3.jpg',
'4.jpg',
'5.png'
);
function preload() {
for (var c = 0; c < arguments.length; c++) {
preloads[preloads.length] = new Image();
preloads[preloads.length - 1].src = arguments[c];
}
}
function rotateImages(flag) {
if (flag == 0)
{
num = num - 1;
if (num < 0)
num = preloads.length;
}
else
{
num = num + 1;
if (num >= preloads.length)
num = 0;
}
if (num == temp) {
rotateImages(1);
} else {
var str = preloads[num].src;
var resArr = str.split("/");
var picName = resArr[resArr.length - 1];
document.getElementById("intro").style.backgroundImage = 'url(./images/slider/' + picName + ')';
temp = num;
setTimeout(function () {
rotateImages(1)
}, speed);
}
}
if (window.addEventListener) {
window.addEventListener('load', function () {
setTimeout(function () {
rotateImages(1)
}, speed)
}, false);
} else {
if (window.attachEvent) {
window.attachEvent('onload', function () {
setTimeout(function () {
rotateImages(1)
}, speed)
});
}
}
</script>
You need to clear the previous timer. Otherwise there will be new timers added with every call to rotateImages(), Save the reference returned from setTimeout() and then use clearTimeout() to clear the timer if it's set
var num = 0;
var temp = 0;
var speed = 5000;
var preloads = [];
var timeout;
preload(
'1.png',
'2.jpg',
'3.jpg',
'4.jpg',
'5.png'
);
function preload() {
for (var c = 0; c < arguments.length; c++) {
preloads[preloads.length] = new Image();
preloads[preloads.length - 1].src = arguments[c];
}
}
function rotateImages(flag) {
if (flag == 0) {
num = num - 1;
if (num < 0)
num = preloads.length;
} else {
num = num + 1;
if (num >= preloads.length)
num = 0;
}
if (num == temp) {
rotateImages(1);
} else {
var str = preloads[num].src;
var resArr = str.split("/");
var picName = resArr[resArr.length - 1];
document.getElementById("intro").style.backgroundImage = 'url(./images/slider/' + picName + ')';
temp = num;
if (!!timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
rotateImages(1);
}, speed);
}
}
if (window.addEventListener) {
window.addEventListener('load', function() {
setTimeout(function() {
rotateImages(1)
}, speed)
}, false);
} else {
if (window.attachEvent) {
window.attachEvent('onload', function() {
setTimeout(function() {
rotateImages(1)
}, speed)
});
}
}

Extend timeout function when button is clicked

This piece of code works, but I am trying to get the timeout function to reset to '0' every time the button is clicked.
var running = false,
count = 0,
run_for = 700;
var end_counter = function() {
if (running) {
running = false;
$("#status").text("Not Running");
alert(count);
started_at = 0;
}
};
$('button').click(function() {
if (running) {
count++;
} else {
running = true;
$("#status").text("Running");
count = 1;
setTimeout(end_counter, run_for);
}
});
Just cancel and restart it:
var timerId,
count = 0;
function end_counter() {
$("#status").text("Not Running");
alert(count);
count = 0;
}
$('button').click(function() {
$("#status").text("Running");
count++;
clearTimeout(timerId);
timerId = setTimeout(end_counter, 700);
});
var running = false,
count = 0,
run_for = 700;
var timer;
var end_counter = function() {
if (running) {
running = false;
$("#status").text("Not Running");
alert(count);
started_at = 0;
}
};
$('button').click(function() {
clearTimeout(timer);
if (running) {
count++;
timer = setTimeout(end_counter, run_for);
} else {
running = true;
$("#status").text("Running");
count = 1;
timer = setTimeout(end_counter, run_for);
}
});
Set timer to a variable - then clear it on click and restart it after count.

Jquery code works, javascript does not, what am i doing wrong?

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).

Categories