Actually I have an update enquery into this point .
I have smth like that :
$(document).ready(function() {
setInterval(doSmth, 10000);
function doSmth() {
var result = document.getElementById("fooText").value;
if (result != "") {
doSmthElse(result);
}
});
}
}
});
I need to activate the interval ,that is fired each 10 seconds, in case only a text control has the focus else do nothing !!
Code for you is:
$(document).ready(function() {
setInterval(function(){
var result = $("#fooText").val();
if (result != "") {
// if
} else {
// else
}
}, 10000);
You can set the interval on focus of the field, and clear it on blur:
var interval;
$(field).focus(function() {
interval = setInterval(doMsth, 10000);
});
$(field).blur(function() {
clearInterval(interval);
});
(the interval var has to be global)
You can implement this in 2 ways,
Let the timer run and inside the function check if the activeElement == <text input>, then execute the rest of the function else return.
$(document).ready(function() {
setInterval(doSmth, 5000);
function doSmth() {
var resultEl = document.getElementById("fooText");
if (document.activeElement.id != resultEl.id) { return false; }
if (resultEl.value != "") {
doSmthElse(resultEl.value);
}
}
function doSmthElse(result) { alert(result);}
});
DEMO here
Set the timer on focus of the text box and remove the timer onblur of the input box.
$('#fooText').focus ( function () {
timer = setInterval(function() {
var textVal = $('#fooText').val();
if (textVal != '') {
doSmthElse(textVal );
}
}, 5000);
});
$('#fooText').blur (function () {
if (timer != '') clearInterval(timer);
});
DEMO here
Related
I have a case where I want a function to fire only when I first type something and fires another function when the I'm done typing (10 seconds idle)
I have this:
var keyPressElements = document.querySelectorAll('#waste-form input,#address,.container .form-control,.widget-box .form-control,#aria-main-search-form-field,#footer-search-field,#aria-feedback-form-field');
keyPressElements.forEach(function(elem) {
elem.addEventListener('keypress', function() {
updateLastTypedTime();
});
});
function updateLastTypedTime() {
if (searchTimeout != undefined)
clearTimeout(searchTimeout);
isUserTyping = true;
console.log("Telling UpdateViewAPI that the user is still typing...");
UpdateViewAPI();
searchTimeout = setTimeout(callServerScript, 10000);
}
function callServerScript() {
console.log("Telling UpdateViewAPI that the user hasn't typed in 10 seconds.");
isUserTyping = false;
UpdateViewAPI();
}
But the issue with this is it triggers the updateLastTypedTime() everytime i type.
Thanks!
It looks like you want another function that's called from updateLastTypedTime only if the user was not already typing, something like:
function updateLastTypedTime() {
if (searchTimeout != undefined)
clearTimeout(searchTimeout);
if (!isUserTyping)
updateStartTyping();
isUserTyping = true;
searchTimeout = setTimeout(callServerScript, 10000);
}
var keyPressElements = document.querySelectorAll("#test-input");
keyPressElements.forEach(function(elem) {
elem.addEventListener('keypress', function() {
updateLastTypedTime();
});
});
var searchTimeout;
var isUserTyping = false;
function updateLastTypedTime() {
if (searchTimeout != undefined)
clearTimeout(searchTimeout);
if (!isUserTyping)
updateStartTyping();
isUserTyping = true;
searchTimeout = setTimeout(callServerScript, 10000);
}
function updateStartTyping() {
console.log("User started typing");
}
function callServerScript() {
console.log("User stopped typing.");
isUserTyping = false;
}
<input type="text" id="test-input">
I have a submit function on a textbox with JavaScript. When the script fires, it checks a Kendo grid for a certain article and adds +1 to its quantity as well as opening the corresponding cell in editing mode. What I want to achieve is that on every submit the timer that starts grid.editCell() will reset its timer.
Currently, the event fires properly. However, the timer doesn't get reset, although the clearTimeout() does work if I just simply start the timer and then clear it right afterwards.
JavaScript:
$('#txtBarcode').submit(function (e) {
var grid = $("#PickListDetailGrid").data("kendoGrid");
var dataSource = $("#PickListDetailGrid").data("kendoGrid").dataSource;
var allData = grid.dataSource.data();
var code = this.value;
var notification = $("#notification").data("kendoNotification");
var timer = null;
clearTimeout(timer);
$.each(allData, function (index, item) {
if (item.ArticleID == code) {
clearTimeout(timer);
timer = null;
if (item.Quantity > item.PickedQuantity && item.PickedQuantity.toString().length < 4) {
var edit = function () {
if (item.PickedQuantity != item.Quantity && timer != null) {
grid.select("tr:eq(" + (index) + ")");
grid.editCell("tr:eq(" + (index + 1) + ") td:eq(" + (5) + ")");
} else {
//do nothing
}
}
item.PickedQuantity++;
item.dirty = true;
dataSource.sync();
if (item.PickedQuantity != item.Quantity) {
console.log("tik tok");
if (timer) {
clearTimeout(timer); //cancel the previous timer.
timer = null;
}
timer = setTimeout(edit, 3000);
} else {
clearTimeout(timer);
timer = null;
}
document.getElementById("txtBarcode").value = "";
} else {
if (item.PickedQuantity.toString().length > 4) {
notification.hide();
notification.show({
message: "Added item"
}, "upload-success");
} else {
notification.hide();
notification.show({
title: "Quantity Error",
message: "You already picked this item to the maximum"
}, "error");
document.getElementById("txtBarcode").value = "";
grid.select("tr:eq(" + (index) + ")");
grid.editCell("tr:eq(" + (index + 1) + ") td:eq(" + (5) + ")");
$('.focus :input').focus();
}
}
}
})
})
You can try delay function like this. The delay function should be outside of the each function.
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
delay(function() {
//do something
}, 3000);
The problem was that var timer = null; had to be outside of the submit function to be properly cleared and set to null before assigning a new setTimeout() to it.
In this fiddle I made a script building a play button for audio files, that allows playing the file only twice and then disables it. But after reloading the page, the button is active again. How can I make sure, the button stays disabled for a defined duration of 30 seconds for example?
I was wrapping my head around localStorage and found a promising question/answer here, but couldn't transfer the knowhow to my usecase. Can someone help me out?
function buildLimitedPlay(selector) {
$(selector).each(function(i) {
var myaudio = $(this)[0];
var button = $(this).next("input.limited-play")[0];
var index = 2;
$(button).css('display', 'block');
$(button).val("Play Clip");
$(myaudio).on('ended', function() {
index--;
$(button).val('Play again');
if (index == 0) {
$(button).css('background', 'red');
$(button).css('cursor', 'not-allowed');
$(button).css('text-decoration', 'line-through');
$(button).disabled;
}
});
$(button).on("click", function() {
if (index > 0) {
myaudio.play();
}
});
});
}
buildLimitedPlay("audio.limited-play");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<audio class="limited-play" preload="none">
<source src="http://www.noiseaddicts.com/samples_1w72b820/3726.mp3" type="audio/mpeg">
</audio>
<input value="Play Clip" class="limited-play" type="button">
I'm assuming you want to automatically enable the play button after the predefined disabled time passes, also you will have multiple audios to play with multiple buttons. here is the code that will work after refresh and automatically enable the button after time out.
$(function () {
function now() { return +new Date }
var db = window.db = {
get: function (key) {
var entry = JSON.parse(localStorage.getItem(key) || "0");
if (!entry) return null;
if (entry.ttl && entry.ttl + entry.now < now()) {
localStorage.removeItem(key);
return null;
}
return entry.value;
},
set: function (key, value, ttl) {
localStorage.setItem(key, JSON.stringify({
ttl: ttl || 0,
now: now(),
value: value
}));
}
};
function buildLimitedPlay(selector) {
$(selector).each(function (i) {
var getRemainingTurn = function () {
var turn = db.get('remainingTurn' + i);
return null == turn ? 2 : turn;
};
var setRemainingTurn = function (turn, timeToLiveInMillisecond) {
db.set('remainingTurn' + i, turn, timeToLiveInMillisecond || 0);
};
var myaudio = this;
var $button = $(this).next("input.limited-play:first");
$button.css('display', 'block')
.on("click", function () {
if (getRemainingTurn() > 0) {
myaudio.play();
}
});
var setAudioState = function (turn) {
$button.val(2 == turn ? 'Play Clip' : 'Play again');
if (turn == 0) {
$button.css({ 'background': 'red', 'cursor': 'not-allowed', 'text-decoration': 'line-through' });
}
else {
$button.css({ 'background': '', 'cursor': '', 'text-decoration': 'none' });
}
};
var disabledPeriodInMillisecond = 30 * 1000;
var tryEnableAudio = function () {
turn = getRemainingTurn();
if (0 == turn) {
//because we don't know how much time passed since it was disabled in case of a page refresh for simplicity.
setTimeout(tryEnableAudio, 50);
return;
}
setAudioState(turn);
};
$(myaudio).on('ended', function () {
var turn = getRemainingTurn();
turn--;
setAudioState(turn);
if (0 == turn) {
setRemainingTurn(turn, disabledPeriodInMillisecond);
tryEnableAudio();
}
else {
setRemainingTurn(turn);
}
});
setAudioState(getRemainingTurn());
tryEnableAudio();
});
}
buildLimitedPlay("audio.limited-play");
});
I am now working on a piece of code of JavaScript which will be used to redirect a page with a shown counter. The problem is, when counter reaches 0, countDown() function gets in an infinite loop which causes the page to remain the same. And of course, I could not resolve the problem yet. Can anyone help?
You can see the problem here:
http://kibristaodtuvarmis.com/index.html
Code is shown below:
var time = 10;
var page = "http://blog.kibristaodtuvarmis.com";
function countDown()
{
if (time == 0)
{
window.location = page;
return(0);
}
else
{
time--;
gett("container").innerHTML = time;
}
}
function gett(id)
{
if(document.getElementById) return document.getElementById(id);
if(document.all) return document.all.id;
if(document.layers) return document.layers.id;
if(window.opera) return window.opera.id;
}
function init()
{
if(gett("container"))
{
setInterval(countDown, 1000);
gett("container").innerHTML = time;
}
else
{
setTimeout(init, 50);
}
}
document.onload = init();
EDIT:
I have done the below changes in countDown() function and problem is resolved:
var control = false;
function countDown()
{
if (time == 0 && control == false)
{
control = true;
window.location = page;
return(0);
}
else if (time > 0)
{
time--;
gett("container").innerHTML = time;
}
else
{
return(0);
}
}
I would do something like this:
var b = false;
if (time == 0 && b == false)
{
b = true;
window.location = page;
return(0);
}
Try this part of code for by replacing your complete javascript Code :
var time = 10;
var page = "http://blog.kibristaodtuvarmis.com";
function startCount() {
time = time - 1;
console.log(time);
document.getElementById("container").innerHTML = time;
startCounter();
}
function startCounter() {
if (time !== 0) {
setTimeout(function () {
startCount();
},1000);
} else {
location.href = page;
}
}
if (window.addEventListener) {
window.addEventListener("load", startCount, false);
} else if (el.attachEvent) {
window.attachEvent("load", startCount);
}
I tried it, It works.
Tell me your reply after testing.
Are you wanting it to stop at 0? Assign the setInterval to a var and then use clearInterval if 0
your setIinterval continues executing before change the window.location and then causes this loop because time is 0 and should launch window.location again
you should clear the interval
var IdInterval = setInterval(function () {
//.... code
}, 10000);
and after the first execution of countDown with time==0 then:
clearInterval(IdInterval);
I want to be able to click a an element with an id of pause to start a count of the elements in a time object and if I re click the pause it will stop it and reclick start it exactly like the toggle feature in JQuery but with a setInteval function how would I go about doing this?
$("#pause").click(function(ffe) {
if(on == true) {
on = false
alert("on");
}
else {
on = true;
alert("off");
}
if(on == false) {
setInterval(function() {
$("#timet ul").append("<li>" + $("#time ul")
.children('li').length +"</li>");
}, 100);
}
else {
alert("Error");
}
});
A classic technique is to use a single master setInterval loop and simply use if..else logic to determine what needs to run. This is how a lot of javascript games work:
var on = true;
// Our master scheduler:
setInterval(function() {
if (on) {
$("#timet ul").append("<li>" + $("#time ul")
.children('li').length +"</li>");
}
}, 100);
// Code to handle the pause button
$("#pause").click(function(ffe) {
on = !on;
}
You can use the setTimeout function, if you want to run the function once, setInterval runs continuously, try the following:
var on = false;
$("#pause").click(function(ffe) {
if (on) {
on = false;
setTimeout(function() {
$("#timet ul").append("<li>" + $("#time ul")
.children('li').length +"</li>");
}, 100);
} else {
on = true;
}
});
You need to use .clearInterval() to stop the execution.
Here is the code: (THE WORKING DEMO)
$("#pause").click((function () {
var interId = null;
var $ul = $("#timet ul");
return function (e) {
if (interId) {
$(this).text("start");
clearInterval(interId);
interId = null;
} else {
$(this).text("pause");
interId = setInterval(function () {
$ul.append($('<li>').text($('li', $ul).length));
}, 100);
}
};
}()));