setInterval & setTimeout? - javascript

I want to stop my javascript after x seconds, I saw that the function is setTimeout, I tried to add that to my code but no succes, is this the better way to do this?
Thanks for your help !
<html>
<head>
<script type="text/javascript">
function blink(){
state = document.getElementsByTagName('img')[0].style.visibility;
if(state == 'hidden'){
newState = 'visible';
}else if(state == 'visible'){
newState = 'hidden';
}
document.getElementsByTagName('img')[0].style.visibility = newState;
}
setInterval('blink();', 300);
</script>
</head>
<body>
<img src="http://ww1.prweb.com/prfiles/2011/10/12/8875514/star_white.jpg" style="visibility:hidden">
</body>
</html>

Initialize your interval in a variable and clear it after X (here 2) seconds:
var interval = setInterval(blink, 300);
setTimeout(function() {
clearInterval(interval);
}, 2000);

use like this:
var myvar;
function myStartFunction()
{
myvar=setInterval(function(){blink()},300);
}
function myStopFunction()
{
clearInterval(myvar);
}

Related

Countdown timer jquery on reset it runs faster then time set

I am trying to make a countdown timer where I can change the value of the countdown or rest the countdown but I am not able to clear the last timer so the value of the timer is added again to speed if increased please help me I am also sharing the code.
var sec = $("#timer_this").val();
$("#start").click(function() {
var sec = $("#timer_this").val();
startTimer('start');
});
$("#reset").click(function() {
$("#timer").html(0);
var timex = 0;
clearTimeout(timex);
var timex = 0;
startTimer('start');
});
$("#stop").click(function() {
$("#timer").html($("#timer_this").val());
clearTimeout(timex);
});
function startTimer() {
timex = setInterval(function() {
//document.getElementById('timer').innerHTML = sec + "sec left";
$("#timer").html(sec);
sec--;
if (sec == -1) {
clearInterval(timex);
time = null;
alert("Time out!! :(");
}
}, 1000);
}
$("#stopbtn").click(function() {
clearTimeout(timex);
});
<script src="https://code.jquery.com/jquery-2.0.3.min.js" integrity="sha256-sTy1mJ4I/LAjFCCdEB4RAvPSmRCb3CU7YqodohyeOLo=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<input type="text" id="timer_this" value="1000">
<span id="timer"></span>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="pause">pause</button>
<button id="reset">reset</button>
several little things to have a working sample :
var timex; should be declared globally if you want to set is value in the several callbacks
in the reset callback you do var timex = 0; first issue you recreate a local function variable timex but you to do it twice that is not valid
for the reset function you can simplyfy it by :
create a stop function
your reset callback became
$("#reset").click(function() {
stopTimer();
startTimer();
});
var sec = $("#timer_this").val();
var timex;
$("#start").click(function() {
var sec = $("#timer_this").val();
startTimer('start');
});
$("#reset").click(function() {
stopTimer();
startTimer();
});
$("#stop").click(stopTimer);
function stopTimer() {
$("#timer").html($("#timer_this").val());
clearTimeout(timex);
timex = undefined;
}
function startTimer() {
if (!timex) {
sec = $("#timer_this").val();
}
timex = setInterval(function() {
$("#timer").html(sec);
sec--;
if (sec == -1) {
clearInterval(timex);
time = null;
alert("Time out!! :(");
}
}, 1000);
}
$("#pause").click(function() {
clearTimeout(timex);
});
<script src="https://code.jquery.com/jquery-2.0.3.min.js" integrity="sha256-sTy1mJ4I/LAjFCCdEB4RAvPSmRCb3CU7YqodohyeOLo=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<input type="text" id="timer_this" value="1000">
<span id="timer"></span>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="pause">pause</button>
<button id="reset">reset</button>
The timex variable was assigned in the scope of the startTimer function and is lost once that function returns, so it is not available when you later come to call clearTimeout on it.
When building out your logic, its often useful to create functions that describe the actions you want to happen, then call them from your UI components. This helps make the code more readable and reduces repetition.
For example, it's simpler to have clearTimeout in one place, and just call it from whichever methods need to stop the timer. It also helps later when getting the UI to reflect the current state of the application since there's only one way to get to that state.
Here's an example of this sort of approach:
let timerx, sec;
$("#start").click(function() {
// Toggle between start/stop
sec ? stopTimer() : startTimer();
});
$("#pause").click(function() {
// Toggle between pause/resume
timerx ? pauseTimer() : resumeTimer();
});
function startTimer() {
// Stop any existing timer
stopTimer();
// Grab the new count
sec = parseInt($("#timer_this").val());
// Start the timer
resumeTimer();
$("#start").text("stop");
$("#pause").prop("disabled", false);
}
function resumeTimer() {
// Start timer
timerx = setInterval(() => {
// Update time remaining
$("#timer").text(--sec);
if (sec === 0) {
// Handle timeout
stopTimer();
alert("Time out!! :(");
}
}, 1000);
$("#timer").text(sec);
$("#pause").text("pause");
}
function stopTimer() {
// Start timer and clear remainng time
sec = 0;
pauseTimer();
$("#timer").text("");
$("#start").text("start");
$("#pause").prop("disabled", true);
}
function pauseTimer() {
// Just stop the timer
timerx = clearInterval(timerx);
$("#pause").text("resume");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type="number" id="timer_this" value="1000">
<button id="start">start</button>
<button id="pause" disabled>pause</button>
<p id="timer"></p>

Javascript clicked and not been clicked for 4 seconds

I have a question about my code. What I'm trying to do is if a certain button is clicked and it isn't clicked again within 4 seconds, a element will be showed and another element hide. But if it is clicked within 4 seconds, it stays the same and so on. I think I should use SetInterval() and ClearInterval(). Currently I have two other functions that do other things. Maybe I can my function there?
Hopefully I have made it clear.
Current javascript code:
var clicks = 0;
function clicks5times() {
clicks = clicks+1;
if(clicks == 6){
document.getElementById('scherm3').style.display = 'block';
document.getElementById('scherm2.2').style.display = 'none';
}
}
var clicked = false;
setInterval(function(){
if (!clicked) {
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
}
},13000);
document.getElementById("buttontimer").addEventListener("click", function(){
clicked = true;
});
Rather than set interval, I would say a timer would be better. Eg:
var clickTimer;
function startTimer() {
clickTimer = window.setTimeout(function(){
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
},4000);
}
function stopTimer() {
window.clearTimeout(clickTimer);
}
function restartTimer() {
stopTimer();
startTimer();
}
document.getElementById("buttontimer").addEventListener("click", function(){
restartTimer();
});
This way when you want to stop the timer or start the timer, you have to just call above functions for other scenarios.
eg:
If you have an init function:
function init() {
...
//some code
startTimer();
}
And maybe call stop timer like so:
function clicks5times() {
...
stopTimer();
}
Split your event handlers in two different functions (eg firstClick and secondClick). The first handler should just add a second event listener and remove it after 4 seconds. For this one-off task, use setTimeout instead of setInterval as you need the task to be done only once after 4 seconds and not every 4 seconds. So I would proceed as follows:
var secondClick = function() {
// DO WHATEVER YOU WANT TO HAPPEN AFTER THE SECOND CLICK
}
var firstClick = function() {
// DO WHATEVER YOU WANT TO HAPPEN AFTER THE FIRST CLICK
document.getElementById("buttontimer").addEventListener("click", secondClick);
setTimeout(function() {
document.getElementById("buttontimer").removeEventListener("click", secondClick);
}, 4000);
};
buttonElement.addEventListener("click", firstClick);
in Javascript
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<button id="buttontimer">fghfgh</button>
</body>
</html><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<button id="buttontimer">fghfgh</button>
<script>
document.getElementById('buttontimer').onclick = function(){
document.getElementById("buttontimer").disabled=true;
setInterval(function(){
if (document.getElementById("buttontimer").disabled == true) {
document.getElementById("buttontimer").disabled = false;
}
},10000);
};
</script>
</body>
</html>
and Jquery
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var button = $('<button>Click Me</button>');
button.clicked = false;
$('body').append(button);
var clicked = false;
button.click(function(){
button.clicked = true;
button.prop('disabled', true);
clicked = true
setInterval(function(){
if (clicked) {
button.prop('disabled', false);
}
},10000);
});
});
</script>
</head>
<body>
</body>
</html>
once u click button disable the property after the timer finish enable back the property

Show reset button after counter reaches zero

I would like to hide and then show the "Reset" button as soon as the counter reaches zero.
Index.html:
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript" src="countdown.js"></script>
</head>
<body>
<input type="text" id="timer">
<script type="text/javascript">
timer = new Countdown();
timer.init();
</script>
<button id="reset">Reset</button>
<script type="text/javascript">
$("#reset").click(function(){
//timer = new Countdown();
timer.reset();
});
</script>
</body>
</html>
Please see http://jsfiddle.net/orokusaki/o4ak8wzs/1/ for countdown.js
AWolf's answer is a bit fancier than mine, and they made some good points about your code, but I tried to keep mine simple and tried not to change your original code too much.
Your init() function will now hide the Reset button, and I had the update_target() function show the Reset button when the timer expired.
Fiddle: http://jsfiddle.net/rgutierrez1014/o4ak8wzs/4/
In this jsFiddle you'll find the updated code and how you could add that behaviour.
I've also improved your code a bit. It's easier to write Countdown.prototype = { init: function() {...}, ...} then writing Countdown.prototype.init = function() {...}
I also changed your setInterval to setTimeout and start a new timeout every second. That's easier and you don't need to clear the interval at the end. Also the callback function for your interval seemed a bit strange and that probably won't work.
You could add your click handlers in the init method of your countdown object like this $('#start').click(this.start.bind(this)); the .bind(this) is used to change the context inside the click handler to the currently used object. Then this inside of the handler is your object and you can access everything with this.
To hide the reset button at start I've used the css display: none; and if you are at zero then show the button with $('#reset').fadeIn('slow'); or $('#reset').show(); if you don't want the animation.
Update 13.03.2015
As mentioned in the comments I've improved the code and now I'm using a jQuery Countdown plugin.
Please have a look at the latest version in this jsFiddle.
I think it's much better then the other code.
(function () {
function Countdown() {
this.start_time = "00:30";
this.target_id = "#timer";
//this.name = "timer";
}
Countdown.prototype = {
init: function () {
console.log('init called');
this.reset();
$('#start').click(this.start.bind(this));
$('#reset').click(this.reset.bind(this));
},
reset: function () {
time = this.start_time.split(":");
//this.minutes = parseInt(time[0]);
this.seconds = parseInt(time[1]);
this.update_target();
},
tick: function () {
if (this.seconds > 0) //|| this.minutes > 0)
{
if (this.seconds == 0) {
// this.minutes = this.minutes - 1;
this.seconds = 59
} else {
this.seconds = this.seconds - 1;
}
this.start();
}
else {
// show reset button
$('#reset').fadeIn('slow');
}
this.update_target();
},
start: function() {
console.log('start called');
//setTimeout(this.name + '.tick()', 1000);
setTimeout(this.tick.bind(this), 1000);
},
update_target: function () {
seconds = this.seconds;
if (seconds < 10) seconds = "" + seconds;
$(this.target_id).val(this.seconds);
}
};
var counter = new Countdown();
counter.init();
})();
#reset {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timer">
<button id="start">Start</button>
<button id="reset">Reset</button>

Can I have setInterval and setTimeout at the same time?

According to this thread: how many javascript setTimeout/ setInterval call can be set simultaneously in one page? it is possible to have multiple setIntervals at the sametime.
However, is it possible to have a setInterval and setTimeout at the sametime?
This is not working...
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
init();
});
function init() {
$('#startbutton').on('click', handleClick);
}
</script>
</head>
<body>
<script>
var playBeep = function () {
var snd = new Audio("beep-7.wav");
snd.play();
}
var handleClick = function () {
var interval1 = setInterval(updateDisplay, 1);
makeIntervals([1,2,3], playBeep);
}
var makeIntervals = function(timeList,callback){
intervals = []
for(i in timeList){
intervals.push(setTimeout(callback,timeList[i]))
}
return intervals
}
function updateDisplay() {
var value = parseInt($('#timer').find('.value').text(), 10);
value++;
$('#timer').find('.value').text(value);
}
</script>
<button type="button" id="startbutton">Play Beep</button>
<P>
<div id="timer"><span class="value">0</span> ms</div>
<P>
Of course. However just make sure you don't have too many.

How to perform an action every couple of seconds?

Can someone quickly and simply explain to me how to perform an action every couple of seconds using
var timeOut = setTimeout(FunctionName, 5000);
I want to run a function every 5 seconds.
As you asked for a method using setTimeout:
function doStuff() {
console.log("hello!");
setTimeout(doStuff, 5000);
}
setTimeout(doStuff, 5000);
But it would probably be better to use setInterval:
function doStuff() {
console.log("hello!");
}
setInterval(doStuff, 5000);
Just put setTimeout at the end inside your function, with a call to itself - like a delayed tail-recursion.
Use setInterval:
var timeOut = setInterval(nextNotice, 5000);
var myFunction = function() {
//Do stuff
AnotherFunction();
};
var timeOut = setInterval(myFunction, 2000);
you can do something like:
$(document).ready(function ()
{
setTimeout(nextNotice, 5000);
}
function nextNotice()
{
// do stuff
setTimeout(nextNotice, 5000);
}
In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.
<html>
<head>
<script type="text/javascript">
var c = 0;
var t;
var timer_is_on = false;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
t = setTimeout(timedCount, 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = true;
timedCount();
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt" />
</form>
</body>
</html>

Categories

Resources