javascript timer not working - javascript

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/

Related

How to create an “unlimited” number of independent timers as individual list items in an unordered list with Javascript or jQuery?

I am trying to write a function which when executed (e.g. user clicks a button or image) creates and displays a new timer as a new list item in an unordered list (jQuery Sortable list). It doesn’t need to be super accurate so SetInterval should work fine. It doesn’t need any stops or resets. I would like the user to be able to create as many new independent (count-up) timers (as list items) in the list as they want, theoretically (although in reality there will likely be less than 10-15 on the go at the same time).
The following code does achieve this (or at least does the first time it is run). Subsequent clicks cause grief as I suspect that the same id is being used more than once for both “minutes” and “seconds” causing a conflict between list items.
function listTimer() {
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval (function(){
document.getElementById("seconds").innerHTML=pad(++sec%60);
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));
}, 1000);
$(document).ready(function(){
$("#sortable1").append('<li class="ui-state-default">' + '<span id="minutes">' + '' + '</span>' + ':' + '<span id="seconds">' + '' + '</span>' + '</li>');
});
}
To allow multiple timers I then figured that each time the function is executed, the values should increment so they are seen as separate. As such I tried
Var i = 0;
function listTimer() {
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval (function(){
document.getElementById("seconds"+i).innerHTML=pad(++sec%60);
document.getElementById("minutes"+i).innerHTML=pad(parseInt(sec/60,10));
}, 1000);
$(document).ready(function(){
$("#sortable1").append('<li class="ui-state-default">' + '<span id="minutes"+i>' + '' + '</span>' + ':' + '<span id="seconds"+i>' + '' + '</span>' + '</li>');
i=++;
});
}
The “seconds” + i ( and “minutes” =i ) in the .innerHTML works because if I leave var i=0 and then hard code “seconds0” and “minutes0” (instead of “seconds”+i etc) in the span id, a timer is generated as planned (once). The trick is that the “seconds” + i (and “minutes” =i ) in the span id do not work as I imagined. If I leave it as per the code above (e.g. in both the .innerHTML and span id) no list item is generated. I suspect the problem is in incrementing the span id.
Addressing the “span id=” to increment it (multiple ways) does not seem to have helped.
I have tried declaring and inserting a variable with no luck:
var newSeconds= “seconds” +i;
var newMinutes= “seconds” +i;
$(document).ready(function(){
$("#sortable1").append('<li class="ui-state-default">' + '<span id=newMinutes >' + '' + '</span>' + ':' + '<span id=newSeconds>' + '' + '</span>' + '</li>');
I have tried changing the id of the span just prior to the append with either:
document.getElementById("seconds").setAttribute("id", "seconds" +i);
document.getElementById("minutes").setAttribute("id", "minutes" + i);
or
document.getElementById("seconds").id("seconds" +i);
document.getElementById("minutes").id ("minutes" + i);
or
var newSeconds= “seconds” +i;
var newMinutes= “seconds” +i;
document.getElementById("seconds").setAttribute("id", newSeconds);
document.getElementById("minutes").setAttribute("id", newMinutes);
or by combinations of these e.g putting quotation marks around the newSeconds/newMinutes in both the .id and .setAttribute.
but I can’t seem to make the append method work and create a new independent list timer each time the trigger is clicked. The timers jump all over the place (or not at all) when the function is executed multiple times.
I have tried searching for javascript or jQuery ways of doing this but I can only seem to see previous questions that revolve around a certain number of timers (and hard coding them e.g. timer1, timer2 etc) rather than an "unlimited" number of timers. I have looked at books on Javascript and jQuery but can't seem to nut out the solution.
I am hoping I have given a minimal reproducible example. I am obviously missing fundamental issues but am unconscious incompetent at the moment. Is anyone happy to show me the error of my ways and help me get the function working?
I think that the issue stems from your referring to the timers by their Id attributes - an Id attribute is supposed to appear once per page, so having it appear in each timer will definitely cause some confusion.
I would recommend a different structure as well for organization. Here are my thoughts in pseudocode (leaving the implementation up to you)
const $timerContainerDiv = $("…"); // the place where timers live
var timers = []; // this is an array containing all of your timers
// function to add a new timer to the array
var addTimer = function(int minutes, int seconds, int title) {
// html that defines the actual structure of the timer,
// including elements for hours and minutes, each identifiable
// by a js class, and each one including a data attribute giving its value
// for example:
var $timer = $("<div class='timer' data-minutes='" + minutes + "' data-seconds='" + seconds + "' title='" + title + "'>");
timers.push(timer);
}
// now define a timer function to update all timers once per second
var updateTimers = function() {
// update each timer, decrementing one second
$.each(timers, function(index, val) {
var $timer = $(val);
var minutes = $timer.data("minutes");
var seconds = $timer.data("seconds");
var title = $timer.attr("title");
seconds--;
// need logic for when seconds goes negative to reset to 59 and decrement minutes
// need logic for when timer done, etc
$timer.empty();
$timer.append("<span>" + title + ": " + minutes + ":" + seconds + " remaining</span>");
});
setTimeout(updateTimers,1000); // call itself
}
updateTimers(); // get the whole thing started

SoundCloud player from stream unable to get duration

I am currently trying to make a progress bar for my own custom player. For some reason, getDuration() is returning a value whether it is treated like the widget's getDuration with a callback function or as if it just pulling a value.
(duration is declared globally which after testing doesn't seem to make a difference in the problem)
duration = player.getDuration();
var minutes = (duration / 1000) / 60;
var strMin = "" + Math.floor(minutes);
var strSec = "" + Math.floor((minutes - Math.floor(minutes)) * 60);
var pad = "00";
var text = strMin + ":" + pad.substring(0, pad.length - strSec.length) + strSec;
$('#bufferText').html(text);
This is how the API says it would be handled based on description and it is how the other methods from the class work but passing in a callback function also does not work.
For anyone that isn't thinking straight like I was, the player doesn't pull any of the information until buffering/playback starts. Putting the code excerpt inside of a listener for the play-start event of the player fixed the issue.

can't change variable value javascript

So I'm working on a script that will save every second a person was online on whatsapp (on whatsapp web)
and I have this:
//add zeros (run only once)
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
//Inject jQuery (run only once)
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
// make online log
//start
var online = "yes";
var onlineCheck1 = window.setInterval(function() {
var x = $('#main>header>div.chat-body>div.chat-status>span').text()
var name = $('#main>header>div.chat-body>div.chat-main>.chat-title>span').text()
var d = new Date();
if (x == "online") {
var online = "yes";
console.log(d.toLocaleDateString('en-GB') + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + name + " " + "was" + " " + "///online///");
} else if (online == "yes") {
console.log("<------------>")
var online = "no";
} else {
var online = "no";
}
}, 1000); //end
and it's logging when someone is online but I want it to put just one mark (<------------>) when the person is offline and it's not doing that.
so what I want this script to do is: make the variable "online" with the value "yes" then make the variable "x" with the value the inner text of an element (which is online or last seen.....) and then look if x is online? then change the value of "online" to "yes" log the date and time if not and if the value of the variable "online" is "yes"? then log a mark (<------------>) and change the value of "online" to "no" if not? then just change the value of the variable "online" to "no" and repeat.
I don't know what is going wrong but it may be that the variables are not getting changed for some reason.
Note: i'm using chrome's console to run this script on web.whatsapp.com so you can try it if you want to see what I mean.
First off, your code looks somewhat dirty - put function out of setInterval.
Secondly, what if the Jquery script from google, injected at the beginning of the code, gets stuck and $ is not defined when you call it?
Then, use setTimeout and call it recursively instead of setInterval.
As for your variable "online" - you use "var" inside your function, so "var online" is created within your anon. function`s scope and the external "var online" is not affected by your manipulations. Try to remove "var" word inside your anon. function in setInterval.
Try to remove the "var" keyword from the variables you want to change inside the if-else statements...

How to write arguments in function?

I have been using functions but I am not able to tackle this.
What I have done is created a function, then made this to use the values provided by the document class or ids and do the work. Once work is done then just give the data back! It worked!
Now I want to make this function happen for two divs, the first function works good. The issue is with the second one. The function is correct, their is some other bug while writing the result.
Here is my code:
function time_untilCom(id) {
var Time2 = Date.parse(document.getElementById("time_" + 2).value);
var curTime2 = new Date();
var timeToWrite2 = "";
var seconds2 = Math.floor((curTime2 - Time2) / (1000));
if (seconds2 > 0 && seconds2 < 60) {// seconds..
timeToWrite2 = seconds2 + " seconds ago";
$('#update_' + 2).html(seconds2);
$('#jstime_' + 2).html(timeToWrite2 + " <b>Time that was captured!</b>");
}
}
If I use it as it is, it works! The issue comes when I try to replace these
("time_" + 2), ("#update_" + 2), ("#jstime" + 2) with ("time_" + id), ("#update_" + id), ("#jstime_" + id).
What i want to happen is that the function would be provided with a common ID that is applied throughout the div and use that ID, to get the value of time, convert it to seconds, do other stuff and then provide me with the result in the corresponding element with the id that was in the argument.
function works great, it do provide me with the result. But the issue is with the id its not being sent I guess. Or if is being sent then not being applied. What might be the issue here? And don't mind the seconds i have that covered too.
I am really very sorry for short code:
Pardon me, I was about to write the code for the function too. But electricity ran out!
Here is the code: onload="time_untilCom('2'), this is the way I am executing this.
And once in the main code, it will be executed like this: onload="time_untilCom(#row.Id) because I am using ASP.NET Web Pages I will be using the server side code to write the ID from Database. And will then user the ID throughtout the div to update the time!
From what I understand, you probably want to replace the second line
var Time2 = Date.parse(document.getElementById("time_" + 2).value);
with
var Time2 = Date.parse(document.getElementById(id).value);
And at the end you can also use
$('#'+id).html(timeToWrite2 + " <b>Time that was captured!</b>");
You are passing "id" as an argument, but you never use it inside the function. My question is: In your example you are using 2 as appendix to id attributes. Is it the 2 (or other numbers respectively) that you want to have as the id parameter of the function?
Then you could just replace each + 2 in your code by + id
function time_untilCom(id) {
var Time2 = Date.parse(document.getElementById("time_" + id).value);
var curTime2 = new Date();
var timeToWrite2 = "";
var seconds2 = Math.floor((curTime2 - Time2) / (1000));
if (seconds2 > 0 && seconds2 < 60) {// seconds..
timeToWrite2 = seconds2 + " seconds ago";
$('#update_' + id).html(seconds2);
$('#jstime_' + id).html(timeToWrite2 + " <b>Time that was captured!</b>");
}
}
EDIT: Please tell us where and how exactly do you call time_untilCom? Did you pass the id there?

Converting hard coded JQuery to a plugin - syntax issues

I have some JQuery that loads one of many elements, for example one <li> in an unordered list out of many rows of list items as such:
this.randomtip = function(){
var length = $("#tips li").length;
var ran = Math.floor(Math.random()*length) + 1;
$("#tips li:nth-child(" + ran + ")").show();
};
$(document).ready(function(){
randomtip();
});
However, I thought it would be nice to convert this to a JQuery plugin to make it more global in use so I could simply call it when I need it for different elements and use cases.
I realized I needed to take the specific selectors out and convert them to $(this) probably based on looking at some code of other JQuery plugins.
This is what I have so far but am getting alot of syntax errors. I have tried many different iterations of the same thing for several hours but no joy:
(function ( $ ) {
$.fn.randomtip = function () {
var length = $(this).length;
var ran = Math.floor(Math.random()*length) + 1;
$(this).find (':nth-child' '+ ran + ')").show();
})(jQuery);
Where I am getting the syntax error is where I have:
$(this).find (':nth-child' '+ ran + ')").show();
You have a few typos on the $(this).find() line. Below is the correct version:
(function ( $ ) {
$.fn.randomtip = function () {
var length = $(this).length;
var ran = Math.floor(Math.random() * length) + 1;
$(this).find (':nth-child('+ ran + ')').show();
})(jQuery);
There is a syntax problem in
$(this).find (':nth-child' '+ ran + ')").show();
Maybe you want this?
$(this).find (':nth-child(' + ran + ')').show();

Categories

Resources