Function is not defined? [duplicate] - javascript

This question already has answers here:
Why does firebug say my function call is "undefined"
(2 answers)
Pass parameters in setInterval function
(19 answers)
Closed 8 years ago.
I have this code: (Stripped pieces not related to question)
$(function() {
mins = 0; //Set the number of minutes you need
//secs = 0;
function Decrement(mins){
var secs = mins * 60;
var currentSeconds = 0;
var currentMinutes = 0;
if(currentSeconds <= 9){ currentSeconds = "0" + currentSeconds; }
secs--;
document.getElementById("commercial").innerHTML = "Please wait "+currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
if(secs !== -1){ alert("Done!"); }
}
function runCommercial(time){
$('#commercial').html('Plase wait 8:00');
$('#commercial').attr("disabled", "disabled");
mins = 8;
setInterval('Decrement(8)',1000);
}
$('#commercial').click(function(){
runCommercial(30);
});
});
Whenever I click the commercial button, the button text gets set to 8:00 as it should, altough it won't count down, instead it gives me "Decrement() is not defined" in the dev console of firefox. Why is this happening and how do I fix it?
Thanks.

This is happening because the String 'Decrement(8)' is being evaluated in the global namespace, not under your IIFE closure.
Change
setInterval('Decrement(8)',1000);
To
setInterval(function () {Decrement(8);}, 1000);
It's considered bad practice to cause an eval-style interpretation of code, try to always pass functions into setTimeout and setInterval, etc.

Related

Create a number sequence function that runs on a timer [duplicate]

This question already has answers here:
Javascript: Increment count by 5 for a variable inside a setInterval() function
(4 answers)
Closed 4 years ago.
I need to take a number (ex. 100), then in 10 seconds add 100 to it. In another 10 seconds, add 100 again to create a running total.
How would I create a function to keep a running total, and have it on a timer that fires every 10 seconds?
You can do it using setInterval
Here in eachInterval function it calls the function (given in setInterval ) and add the value to total and display in console. You can pass time in function as per you need
let total = 100;
let interval;
function eachInterval(time){
interval = setInterval(()=>{
total+=100;
console.log(total)
},time)
}
setTimeout(()=>{
clearInterval(interval)
},5000)
eachInterval(1000)
function createsequence(){
var number = 100;
console.log(number)
//setInterval run at gap of 10 secs use it instead of timer
var interval = setInterval(function(){
//increment number
number += 100;
console.log(number)
},10000);
//10000ms is 10 secs
}
createsequence()

Javascript Second Counter

On my website, I am trying to count (and display) how many seconds (not minutes or hours) the user has been on my site. So, if they have been on it for 5 minutes, it will display 300, Not 5 minutes.
I am Very Unexperienced with JavaScript, So please help.
You can use the setInterval function to run another function as often as you choose. For example:
var seconds = 0;
var el = document.getElementById('seconds-counter');
function incrementSeconds() {
seconds += 1;
el.innerText = "You have been here for " + seconds + " seconds.";
}
var cancel = setInterval(incrementSeconds, 1000);
<div id='seconds-counter'> </div>
If you run this snippet, you'll see the counter working.
The setInterval function takes two parameters:
the function you want to call
the number of milliseconds between calls
Since you want to call increment the counter every second, you want to use 1000 milliseconds (1 second).
For more details, see the MDN documentation for setInterval.
My answer is similar to the one above but I'll give it anyway. This will only work on a single page so hopefully your site already runs on AJAX.
window.setInterval((function(){
var start = Date.now();
var textNode = document.createTextNode('0');
document.getElementById('seconds').appendChild(textNode);
return function() {
textNode.data = Math.floor((Date.now()-start)/1000);
};
}()), 1000);
You've been on this page for <span id=seconds></span> seconds.

javascript timer not working

I have a little javascript which I'm trying to use to make a timer. I got the code from another question on this site and it works ok on it's own, but since I'm making a few timers on this page I need to modify it a little and my modifications break it.
I'm not so brilliant with javascript and I can't see where I'm going wrong. All I've really done is add numerals (the id's of the products which have the timers) to the variable and function names. I've read it's ok to have numerals in variable and function names, so I'm at a loss.
The code I'm using (which isn't working) is:
$(document).ready(function () {
var x1, secs1 = 61434; //declared globally
x1 = setInterval(myFunc1, 1000);
function myFunc1() {
alert('yo');
var minutes = Math.floor(secs1 / 60);
var seconds = secs1 % 60;
$('#timer_'1).html(minutes + ':' + seconds); //assuming there is a label with id 'timer'
secs1--;
if (secs1 == 0) {
document.getElementById('timer').style.hidden = true;
clearInterval(x1);
}
}
});
Your question is unclear, and it's not obvious to me what you're trying to do. But one obvious problem is in these two lines:
$('#timer_'
1).html(minutes + ':' + seconds); //assuming there is a label with id 'timer'
That will throw a syntax error, because '#timer_'1 is not valid syntax.
Two issues here with the css selectors:
$('#timer_'1).html(minutes + ':' + seconds); //add a + between timer_ and 1
document.getElementById('timer') //should be timer_1 too
fiddle http://jsfiddle.net/Drea/1zvLspxd/

Adding leading zeros to a Javascript timer

I'm attempted to add leading zeros to the seconds value and I keep running into errors. I've tried a number of selected solutions posted here and can't seem to make it work.
I'm pulling values from the spans because those values are coming from the database.
var timer = $('.timer');
$('.prev-button,.next-button').hide();
setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (m.length == 0 && parseInt(s.html()) <= 0) {
timer.html('Proceed to the Next Slide');
$('.prev-button,.next-button').fadeIn();
}
if (parseInt(s.html()) <= 0) {
m.html(parseInt(m.html() - 1));
s.html(60);
}
if (parseInt(s.html()) < 10) {
$('.sec').prepend(0)
}
if (parseInt(m.html()) <= 0) {
timer.html('Time remaining for this slide - <span class="sec">59</span> seconds')
}
s.html(parseInt(s.html() -1));
}, 1000);
http://jsfiddle.net/certainstrings/a2uJ2/1/
I've modified your Fiddle to make it work. http://jsfiddle.net/a2uJ2/3/
You should store the time in javascript int vars instead of reading it from the html elements every time. This causes maintainability problem as you are attaching logic to the layout of your html document.
I haven't fixed all your code but i've created two variables that are used to perform the calculations instead.
Couple of things: You'd be better off registering a start time, and comparing against that inside the interval function. Timers are not guaranteed to be precise, but will instead trigger on or after the interval you specify. If the computer's busy, the timer might be late.
Also, if you're using parseInt, always, always specify a radix argument (the number base). If you don't, the string "08" will will be parsed to "0" because a leading zero is intepreted as an octal (base-8). So use parseInt(string, 10) to parse to a normal base-10 number.
As for adding the leading zero, I'd say you should keep a couple variable for total amount of seconds, rather than reading/writing to the elements all the time.
Updated you jsfiddle
var duration, startTime, interval;
duration = parseInt($(".min").text(), 10) * 60 + parseInt($(".sec").text(), 10);
startTime = (new Date()).getTime();
function countDown() {
var elapsed, remaining, m, s;
elapsed = ((new Date()).getTime() - startTime) / 1000;
remaining = duration - elapsed;
if(remaining <= 0) {
clearInterval(interval);
$(".timer").text('Proceed to the Next Slide');
$('.prev-button,.next-button').fadeIn();
} else {
m = String(Math.round(remaining / 60));
s = String(Math.round(remaining % 60));
if( s < 10 ) {
s = "0" + s;
}
$(".min").text(m);
$(".sec").text(s);
}
}
interval = setInterval(countDown, 500);
This is just a minimal change from you code. I'd probably do something fundamentally different to keep the markup and JS as separate as possible, and so on and so forth, but this works too.
try it like this:
if (parseInt(s.html()) < 10) {
$('.sec').val('0' + $('.sec').val());
}
You're going to need to treat the value as a string rather than as an int. JavaScript is pretty aggressive about converting things that look like numbers into numbers, and that's what's happening here.

Different backgrounds for different time of day? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Changing background based on time of day (using javascript)
I'm looking to create a site where the background rotates a bunch on files for different times of day. Is there any way I can tie maybe a bit of javascript to change the background at certain times based on the either the server or script clock?
I'm looking to have a day/afternoon/evening/night/dawn set of backgrounds that I want to cycle through.
Using the code in this question, fetch the local time, and change the CSS of the element, which keeps the background.
You could do something like this, and then just pass the i variable to the element background-image:
var d = new Date(),
h = d.getHours(),
i;
if (h < 6) i = "night.jpg";
else if (h < 9) i = "dawn.jpg";
else if (h < 15) i = "afternoon.jpg";
else if (h < 21) i = "day.jpg";
else i = "night.jpg";
document.body.style.background = "url("+i+")";
http://jsfiddle.net/niklasvh/UZG9z/
Add this into the head of your HTML document:
<script type="text/javascript">
(function(){
var styles = ['night', 'dawn', 'afternoon', 'day', 'evening'];
var currStyle = styles[Math.floor(styles.length * (new Date()).getHours() / 24)];
document.documentElement.className += ' ' + currStyle;
}());
</script>
Then in your CSS you can use something like this:
.night #myelement {
background-image: url(myImage.jpg);
}
.day body {
background-color: red;
}

Categories

Resources