Can I have setInterval and setTimeout at the same time? - javascript

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.

Related

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

Manually set interval time for setInterval

I'm trying to create application where the user can select how often they want the counter to increment by. For example, they type into the input box that they want it to increment by 1 every 5 seconds, and the setInterval will be set to 5 seconds, etc. Here's what I have so far:
<input type="text" id="timer"></input>
<input type="button" onlick="setTime()" value="test" />
<h1>0</h1>
<button class="play">Play</button>
<button class="pause">Pause</button>
<script type="text/javascript">
function setTime() {
var output = $('h1');
var isPaused = true;
var count = 0;
timer = document.getElementById("timer").value;
setInterval(function() {
if(!isPaused) {
time++;
output.text(time);
}
}, timer*1000);
}
//with jquery
$('.pause').on('click', function(e) {
e.preventDefault();
isPaused = true;
});
$('.play').on('click', function(e) {
e.preventDefault();
isPaused = false;
});
</script>
Can I get any ideas or help? I appreciate it in advance
Refactoring a little your code, you can do it this way:
Every <input type="text" id="timer"></input>Seconds<br>
<button class="start">Start</button>
<h1>0</h1>
<button class="play">Play</button>
<button class="pause">Pause</button>
And the JS:
var interval = null;
var time = 0;
var output = $('h1');
function setTimer() {
var seconds = +($("#timer").val());//Get the user input (and convert to number)
interval = setInterval(function() {
time++;
output.text( time );
}, seconds*1000);
}
//with jquery
$('.pause').on('click', function(e) {
e.preventDefault();
if(interval){
clearInterval(interval);//Clear the created interval
}
});
$('.play').on('click', function(e) {
e.preventDefault();
setTimer();
});
$('.start').click(function(){
time = 0;
setTimer();
});
See the working example here: https://output.jsbin.com/cukehijuwo/
Each time the user calls setTime, you are creating another interval. These will continue to be created throughout the lifecycle of your application. You should remove timeouts before creating new ones:
var timeoutID = null;
function setTime() {
...
clearTimeout(timeoutID);
timeoutID = setTimeout(function() {
...
}, timer * 1000);
}
For reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval
Full simple tested program, hope this will help you
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
function display() {
$("h1").html(parseInt($("#inc").val()) + parseInt($("h1").html())) ;
t = setTimeout("display()",parseInt($("#int").val())*1000)
}
function pauseT(){
clearTimeout(t);
}
function continueT(){
t = setTimeout("display()",parseInt($("#int").val())*1000)
}
</script>
Increment Value<input type="text" id="inc"></input>
Interval in Second<input type="text" id="int"></input>
<input type="button" onclick="display()" value="Start" />
<h1>0</h1>
<button onclick="continueT()">Continue</button>
<button onclick="pauseT()">Pause</button>

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>

How to repeat a div in every minute

This is my code. Here the div is animated after 5 sec and hidden after another 5 sec. I need to repeat this every 5 sec. That means every 5 second the div will animate and disappear after another 5 second.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="jquery.animate-colors.js"></script>
<script type="text/javascript" src="jquery.animate-colors.min.js"></script>
<script>
$(window).load(function(){
$('#div').delay(5000).fadeIn(function() {
$(this).text('Some other text!').css({'text-align':'center',})
});
$("#div").animate({
left:'450px',
opacity:'0.5',
height:'250px',
width:'250px',
border:'3px solid',
borderColor: 'darkolivegreen',
backgroundColor: '#cccc'
})
$('#div').delay(5000).fadeOut();
});
</script>
</head>
<body>
<div id="div" style="background:#98bf21;height:100px;width:100px;position:absolute;">Please login</div>
</body>
</html>
You could use the setInterval() method in javascript.
Summary
Calls a function or executes a code snippet repeatedly, with a fixed
time delay between each call to that function.
MDN Documentation
I've just wrapped your code in the "fader" function, then on document load, setInterval will run every 10 seconds.
<script>
function fader () {
$('#div').delay(5000).fadeIn(function() {
$(this).text('Some other text!').css({'text-align':'center',})
});
$("#div").animate({
left:'450px',
opacity:'0.5',
height:'250px',
width:'250px',
border:'3px solid',
borderColor: 'darkolivegreen',
backgroundColor: '#cccc'
})
$('#div').delay(5000).fadeOut();
};
$(function () {
setInterval(fader,10000);
})
</script>
<div id="blinkText"></div>
<script>
// Takes text to blink and id of element to blink text in
function blinkText(text, id) {
// Blink interval
setInterval(blinker, 5000);
// Flag to see what state text is in (true or false)
var flag = true;
// Number of times to blink text
var blinkNum = 10000;
var i = 1;
//you can select whole div by ajax
var divID = document.getElementById(id);
function blinker() {
if (i < blinkNum) {
if (flag) {
divID.innerHTML = text;
flag = false;
} else {
divID.innerHTML = "";
flag = true;
}
i++;
} else {
// Delete if it's still showing
divID.innerHTML = "";
// Stop blinking
clearInterval(blinker);
}
}
}
blinkText("Hello World", "blinkText");
</script>

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