I was working on a Timer code and its working fine but I'm unable to trigger on button click. I believe there is a silly mistake that I'm not able to figure out and was looking for help.
When I click on button, I get following error in console.
Uncaught ReferenceError: startTimer is not defined
I even have tried using $(document).ready() and defined functions in it still no luck.
Code
function timer(){
var time = {
sec:00,
min:00,
hr:00
}
var max = 59;
var interval = null;
function update(str){
time[str]++;
time[str] = time[str]%60;
if(time[str] == 0){
str == "sec"? update("min"):update("hr");
}
print(str);
}
function print(str){
var _time = time[str].toString().length == 1?"0" + time[str]:time[str];
document.getElementById("lbl"+str).innerText = _time;
}
function initInterval(){
interval = setInterval(function(){
update("sec");
},1000);
}
function stopTimer(){
clearInterval(interval);
}
return {
'init': initInterval,
'stop': stopTimer
}
};
var time = new timer();
function startTimer(){
time.init();
}
function endTimer(){
time.stop();
}
<div>
<span id="lblhr">00</span>
: <span id="lblmin">00</span>
: <span id="lblsec">00</span>
</div>
<button onclick="startTimer()">Start</button>
<button onclick="endTimer()">Stop</button>
I'm looking for pure JS solution, and not JQuery($(btnId).on("click")).
Link to JSFiddle
As I mentioned in a comment, using innerText won't work in most browsers, use innerHTML. This should work:
function timer(){
var time = {
sec:00,
min:00,
hr:00
}
var max = 59;
var interval = null;
function update(str){
time[str]++;
time[str] = time[str]%60;
if(time[str] == 0){
str == "sec"? update("min"):update("hr");
}
print(str);
}
function print(str){
var _time = time[str].toString().length == 1?"0" + time[str]:time[str];
document.getElementById("lbl"+str).innerHTML = _time;
}
function initInterval(){
interval = setInterval(function(){
update("sec");
},1000);
}
function stopTimer(){
clearInterval(interval);
}
return {
'init': initInterval,
'stop': stopTimer
}
};
var time = new timer();
function startTimer(){
time.init();
}
function endTimer(){
time.stop();
}
<div>
<span id="lblhr">00</span>
: <span id="lblmin">00</span>
: <span id="lblsec">00</span>
</div>
<button onclick="startTimer()">Start</button>
<button onclick="endTimer()">Stop</button>
So, your jsfiddle doesn't work because jsfiddle isn't expecting you to assign the onclick event in the HTML section.
You need to migrate that to the javascript section. In the HTML you need to assign an id to each button. Then, in the javascript section, have something like
document.getElementById("bStart").onclick = startTimer;
I also noticed that you have startTimer_out() as a function, but your HTML is trying to call startTimer().
Looks like it may just a jsfiddle thing.
Related
So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?
Here's my .js file and the calls I'm making are
input type="button" value="generate" onClick="generation();
input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"
input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.
setInterval returns a handle, you need that handle so you can clear it
easiest, create a var for the handle in your html head, then in your onclick use the var
// in the head
var intervalHandle = null;
// in the onclick to set
intervalHandle = setInterval(....
// in the onclick to clear
clearInterval(intervalHandle);
http://www.w3schools.com/jsref/met_win_clearinterval.asp
clearInterval is applied on the return value of setInterval, like this:
var interval = null;
theSecondButton.onclick = function() {
if (interval === null) {
interval = setInterval(generation, 1000);
}
}
theThirdButton.onclick = function () {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
}
Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.
var genTimer
var stopGen = 0
function generation() {
clearTimeout(genTimer) ///stop additional clicks from initiating more timers
. . .
if(!stopGen) {
genTimer = setTimeout(function(){generation()},1000)
}
}
}
Live demo
This is all you need!
<script type="text/javascript">
var foo = setInterval(timer, 1000);
function timer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
$(document).on("click", "#stop_clock", function() {
clearInterval(foo);
$("#stop_clock").empty().append("Done!");
});
</script>
I am currently setting up two buttons, start and stop for a jquery loop on html5. The start button works perfectly but whatever I try the 'stop' button remains inactive. I have seen many examples about stopping the loop but none seems to resolve the issue in the button being unresponsive. Sorry if this is such a simple question, but as a student I am quite frustrated and thus asking. cheers
"use strict";
var current_banner_num = 1;
$(document).ready(function(){
$("#banner-base").css("visibility","hidden");
$("#banner-"+current_banner_num).show();
var next_button = $("#start").button();
var stop_button = $("#stop").button();
next_button.click(function(){
var timer = setInterval(myCode, 2000);
function myCode() {
//$("#banner-"+current_banner_num).hide();
$("#banner-"+current_banner_num).fadeTo(800, 0);
if (current_banner_num == 4) {
current_banner_num = 1;
}
else {
current_banner_num++;
}
$("#banner-"+current_banner_num).fadeTo(800, 1);
}
});
stop_button.click(function(){
function abortTimer(){
clearInterval(timer);
}
});
});
You are just defining a function again and again here. Just get rid of the function in the event handler:
stop_button.click(function(){
clearInterval(timer);
});
This would execute the clearInterval(), while the code in your original question just defines a function, but doesn't call or do anything as you said. Hope it gets solved.
I think you have 2 problems in your code. timer variable is not visible outside of next_button.click(function(){ ... }); because it is local for this function, so you need to make it a little bit global; second problem is that in stop_button.click(function(){ ... }); you just declare function abortTimer but do not call it (in general, it is not necessary to declare that function). I think your code should be like:
"use strict";
var current_banner_num = 1;
$(document).ready(function(){
$("#banner-base").css("visibility","hidden");
$("#banner-"+current_banner_num).show();
var next_button = $("#start").button();
var stop_button = $("#stop").button();
var timer = null;
next_button.click(function(){
timer = setInterval(function(){
//$("#banner-"+current_banner_num).hide();
$("#banner-"+current_banner_num).fadeTo(800, 0);
if (current_banner_num == 4) {
current_banner_num = 1;
}
else {
current_banner_num++;
}
$("#banner-"+current_banner_num).fadeTo(800, 1);
}, 2000);
});
stop_button.click(function(){
clearInterval(timer);
});
});
Also it wasn't necessary to declare function myCode in nextButton function, so i clear it too for you
Use a global variable instead of a local one ,unwrap the clearInterval function
"use strict";
var current_banner_num = 1;
$(document).ready(function(){
$("#banner-base").css("visibility","hidden");
$("#banner-"+current_banner_num).show();
var next_button = $("#start").button();
var stop_button = $("#stop").button();
var timer = null;
next_button.click(function(){
timer = setInterval(myCode, 2000);
function myCode() {
//$("#banner-"+current_banner_num).hide();
$("#banner-"+current_banner_num).fadeTo(800, 0);
if (current_banner_num == 4) {
current_banner_num = 1;
}
else {
current_banner_num++;
}
$("#banner-"+current_banner_num).fadeTo(800, 1);
}
});
stop_button.click(function(){
clearInterval(timer);
});
});
Hi here is my code i need to bind the values like,
output : test test test
here is my code but working,
<script type="text/javascript">
function delayMsg2() {
var timer = null;
if (timer == null)
{
timer = setInterval(rudy(), 1000);
}
else
{
clearInterval(timer);
timer = null;
}
}
function rudy()
{
document.getElementById("output2").innerHTML = document.getElementById("output2").innerHTML + " test";
}
</script>
<div>
<button onclick="delayMsg2();" >Click me!</button>
<span id="output2"></span>
</div>
what i need to change
Reference your function rudy directly:
timer = setInterval(rudy, 1000);
No need to write a closure around, like in the other answers.
Whats wrong with your code? You execute rudy() at the moment your delay2msg is executed and you pass the return value (which is void), to the setInterval() method. Not good :)
Changed your line
timer = setInterval(rudy(), 1000);
To
timer = setInterval(function(){rudy();}, 1000);
Updated Demo
You have to fix your setInterval declaration
timer = setInterval(function(){rudy()}, 1000);
Here is a fiddle.
change your code with this one and this will solve your problem of start/stop interval also.
var timer = null;
function delayMsg2() {
if (timer == null) {
timer = setInterval(rudy, 1000);
} else {
clearInterval(timer);
timer = null;
}
}
function rudy() {
document.getElementById("output2").innerHTML = document.getElementById("output2").innerHTML + " test";
}
DEMO
I have trouble with timer in button click. When i click button startpause() method is called there i set start timer and stop timer. It works fine when I click button normally(one click after sometime another click) but when I click the button again and again speedly the timer starts to jump with 2-3 secs. Seems like more than one timer is running.. Anyone have any idea....?? here time is my timer method
function startpause() {
if(FLAG_CLICK) {
setTimeout(tim,1000);
FLAG_CLICK = false;
}
else {
clearTimeout(ti);
FLAG_CLICK = true;
}
}
function tim() {
time.innerHTML = t;
t = t + 1;
ti= setTimeout("tim()", 1000);
}
Try this:
// assuming you declared ti and t out here, cuz I hope they're not global
var t = 0;
var ti;
var running = false;
function startpause() {
clearTimeout(ti);
if(!running) {
ti = setTimeout(tim,1000);
running = true;
} else {
running = false;
}
}
function tim() {
time.innerHTML = t;
t = t + 1;
ti = setTimeout(tim,1000);
}
You can read more about the .setTimeout() here: https://developer.mozilla.org/en/docs/DOM/window.setTimeout
Also, see the jsfiddle I just created: http://jsfiddle.net/4BMhd/
You need to store setTimeout somewhere in order to manipulate it later.
var myVar;
function myFunction()
{
myVar=setTimeout(function(){alert("Hello")},3000);
}
function myStopFunction()
{
clearTimeout(myVar);
}
ref http://www.w3schools.com/js/js_timing.asp
Maybe you must change this:
if(FLAG_CLICK) {
setTimeout(tim,1000);
FLAG_CLICK = false;
}
to:
if(FLAG_CLICK) {
tim();
FLAG_CLICK = false;
}
It seems works for me normally
So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?
Here's my .js file and the calls I'm making are
input type="button" value="generate" onClick="generation();
input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"
input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.
setInterval returns a handle, you need that handle so you can clear it
easiest, create a var for the handle in your html head, then in your onclick use the var
// in the head
var intervalHandle = null;
// in the onclick to set
intervalHandle = setInterval(....
// in the onclick to clear
clearInterval(intervalHandle);
http://www.w3schools.com/jsref/met_win_clearinterval.asp
clearInterval is applied on the return value of setInterval, like this:
var interval = null;
theSecondButton.onclick = function() {
if (interval === null) {
interval = setInterval(generation, 1000);
}
}
theThirdButton.onclick = function () {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
}
Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.
var genTimer
var stopGen = 0
function generation() {
clearTimeout(genTimer) ///stop additional clicks from initiating more timers
. . .
if(!stopGen) {
genTimer = setTimeout(function(){generation()},1000)
}
}
}
Live demo
This is all you need!
<script type="text/javascript">
var foo = setInterval(timer, 1000);
function timer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
$(document).on("click", "#stop_clock", function() {
clearInterval(foo);
$("#stop_clock").empty().append("Done!");
});
</script>