Why is this timer working and not working? - javascript

I made a java timer
everything works when all the code is in one file and separated.
When I start doing anything about it
create a separate js file and move the java code there
and even when i try to insert it inside php nawiada
in both cases it stops working
how is it like here it works and it's great.
but i want js in js file then it stops working,
I think it is about "'these elements but I don't know, I'll tire of the timer, best regards
var secs = 0;
var element = "czas";
var T = null;
function count(id)
{
temp = secs;
if(secs > 0)
{
result = Math.floor(temp) + " ";
document.getElementById(element).innerHTML = result;
secs--;
}
else
{
document.location="/"
clearInterval(T);
}
}
function counter(seconds)
{
secs = seconds;
T = window.setInterval("count()", 1000);
}
echo
'<div id="czas"></div>
<script type="text/javascript">counter(60);</script>'
;

Related

Chrome Extensions: Javascript not not running clearInterval();

I'm trying the make a chrome extension in javascript. So far, my popup.js looks like this:
let bg;
let clock;
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('button1').addEventListener('click', butClicked);
bg = chrome.extension.getBackgroundPage();
//clock = document.getElementById("label1");
});
let timeStamp;
let isClockRunning = false;
function butClicked() {
let test = bg.getURL();
document.getElementById('test').innerHTML = test;
timeStamp = new Date();
isClockRunning = !isClockRunning;
runCheckTimer();
}
function runCheckTimer() {
var handle;
if(isClockRunning == true) {
handle = setInterval(updateClock, 1000);
}
else if(isClockRunning == false) {
clearInterval(handle);
handle = 0;
}
}
function updateClock() {
let seconds = bg.returnTimeSince(timeStamp);
document.getElementById("label1").innerHTML = "Seconds: " + seconds;
}
The program works just fine when I click the button once; it starts the timer. But when I click the button the second time, timeStamp gets set to 0, but the updateClock keeps running at the same interval; the interval doesn't get cleared even though I'm toggling the isClockRunning boolean. It's almost as if javascript is forgetting to run the else if part in runCheckTimer(). How can I fix this?
EDIT: On a sidenote, am I doing the timer thing the right way? Or is there a better way to do it? I basically want a timer to keep ticking every second since you've pressed the button, and then when you click it again it'll stop and reset to 0.
You have scoped handle to runCheckTimer. When runCheckTimer starts, it will create a new handle every time.
Move handle outside of the function.
var handle;
function runCheckTimer() {
if(isClockRunning == true) {
handle = setInterval(updateClock, 1000);
}
else if(isClockRunning == false) {
clearInterval(handle);
handle = 0;
}
}

Trigger a jQuery function from another file in JS

How I can call/trigger a jQuery function (which is in another file) from JS.
So basically this is the jQuery function (/js/animation.js).
$('#spin').click(function () {
var tickets = Math.floor(Math.random() * 200) + 1;
if(tickets < 51) {
var winner = 155;
}
else {
var winner = 145;
}
rouletteSpin(winner);
});
I know that its based on a codepen Roulette Animation.
Now the problem is that it should not roll without going through an if statement.
The statement should be a variable using Database info.
That's the point.
In my opinion you cant use PHP / select DB Info in jQuery so I decided to go into my index.php to trigger the jQuery function after the if statement in js went through.
So let me show you my HTML Button + JS Function:
onclick="openCase()
into the first HTML Button tag.
Now the JS Function:
<script>
var credits = CodeToGet_MYSQL_DB_Info_here_written_in_php;
function openCase() {
if(credits > 10000) {
spinIt();
}
else {
alert('Something went wrong');
}
}
And changed the jQuery Function (in path /js/animation.js) to the following:
function spinIt () {
var tickets = Math.floor(Math.random() * 200) + 1;
if(tickets < 51) {
var winner = 155;
}
else {
var winner = 145;
}
rouletteSpin(winner);
});
That is not working. I already googled a lot so please don't flame me.
Already used pretty much every method of this post:
calling Jquery function from javascript
Would be nice if someone can help me out!

Onclick unable to find function

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.

Javascript Countdown that loads ahref

I'm totally a beginner with JavaScript and I'm trying to make a Javascript Countdown that loads an
I'm using this code for the countdown
<script language="Javascript">
var countdown;
var countdown_number;
function countdown_init() {
countdown_number = 11;
countdown_trigger();
}
function countdown_trigger() {
if(countdown_number > 0) {
countdown_number--;
document.getElementById('countdown_text').innerHTML = countdown_number;
if(countdown_number > 0) {
countdown = setTimeout('countdown_trigger()', 1000);
}
}
}
function countdown_clear() {
clearTimeout(countdown);
}
</script>
I want to load exactly this after the count reaches 0... I am totally lost... what should I do?
It is basically a countdown that stops a music player after reaching 0. I would like to set up several countdowns with 10 mins, 15 mins, and 30 mins.
var countdown;
var countdown_number;
function countdown_init(time) {
countdown_number = time;
countdown_trigger();
}
function countdown_trigger() {
if (countdown_number > 0) {
countdown_number--;
document.getElementById('countdown_text').innerHTML = countdown_number;
setTimeout('countdown_trigger()', 1000)
} else { // when reach 0sec
stop_music()
}
}
function stop_music(){
window.location.href = "bgplayer-stop://"; //will redirect you automatically
}
Here is a simple example using mostly what you had above. This will need to be expanded a bit in order to have multiple countdowns but the general idea is here.
Fiddle: http://jsfiddle.net/zp6nfc9b/5/
HTML:
<a id="link_to_click" href="bgplayer-stop://">link</a>
<span id="countdown_text"></span>
JS:
var countdown_number;
var countdown_text = document.getElementById('countdown_text');
var link_to_click = document.getElementById('link_to_click');
function countdown_init() {
countdown_number = 11;
countdown_trigger();
}
function countdown_trigger() {
countdown_number--;
countdown_text.innerHTML = countdown_number;
if (countdown_number > 0) {
setTimeout(
function () {
countdown_trigger();
}, 1000
);
}
else {
link_to_click.click();
}
}
link_to_click.addEventListener('click',
function () {
countdown_text.innerHTML = 'link was clicked after countdown';
}
);
countdown_init();
To explain some portions a little I think overall you had the correct idea.
I only added the eventListener so you could see the link was actually being clicked and displays a message in the countdown_text for you.
You didn't need to check countdown_number more than once so I removed that if block.
Also you don't really need to clear the timeout either. It clears itself once it executes. You only really need to clear a timeout if you want to stop it before it completes but since we rely on the timeout completing in order to do the next step its not necessary.

Pass window.SessionTimeout script to js file

I´m doing an MVC app. And this is in my _Layout.cshtml
I need to move it to a a js file
<script type="text/javascript">
window.SessionTimeout = (function() {
var _timeLeft, _popupTimer, _countDownTimer;
var stopTimers = function() {
window.clearTimeout(_popupTimer);
window.clearTimeout(_countDownTimer);
};
var updateCountDown = function() {
var min = Math.floor(_timeLeft / 60);
var sec = _timeLeft % 60;
if(sec < 10)
sec = "0" + sec;
document.getElementById("CountDownHolder").innerHTML = min + ":" + sec;
if(_timeLeft > 0) {
_timeLeft--;
_countDownTimer = window.setTimeout(updateCountDown, 1000);
} else {
document.location = "Home/TimeOutPage";
}
};
var showPopup = function() {
_timeLeft = 60;
updateCountDown();
ClientTimeoutPopup.Show();
};
var schedulePopup = function() {
stopTimers();
_popupTimer = window.setTimeout(showPopup, #PopupShowDelay);
};
var sendKeepAlive = function() {
stopTimers();
ClientTimeoutPopup.Hide();
SessionTimeout.schedulePopup();
};
return {
schedulePopup: schedulePopup,
sendKeepAlive: sendKeepAlive
};
})();
I try to copy only the code between the script tag but it doesn't work. I know the problem is with the function signature
window.SessionTimeout = (function() { ...
but i don´t know hot to use window.SessionTimeout in a js file.
The #PopupShowDelay is define in my view like this:
#functions {
public int PopupShowDelay
{
get { return 60000 * (Session.Timeout - 1); }
}
}
UPDATE
Ok, i found the error.
The problem is the variable
#PopupShowDelay
I defined that at the view and was trying to read the .js file.
So, i'm going tho check this:
Passing parameters to JavaScript files
Thankls!!
You could have problems with this context in the nested function.
You can read more here
your code should be working, if you linked the file in a script tag at the end of your template's document body and the file is being loaded correctly (test with a console.log if your code is executed).

Categories