Waiting for webworker to finish - javascript

I have a webworker that does certain things in the background. After it is done , an event is triggered by it. I want pause the execution of my program till i get that event fired. In short i need to wait for that event to occur and after it is fired i need to resume the rest of my functionality. I been searching all over the internet and i couldn't find a suitable solution for this.
var worker = new Worker( workInBackground );
var workInBackground = function () {
//some stuff
$(document).trigger("done")
}
I need to pause for "done" to be fired and then continue my call-stack. I would really appreciate some help here

Just a timer, checking for a variable.
var checkWorkDone = false;
var workController = setInterval(function(){ CheckWork() }, 200);
function CheckWork() {
console.log("checkWorkDone = " + checkWorkDone );
if(checkWorkDone == true)
{
goOnToDoNextJob();
}
}
// when checkWorkDone == true, the work is done, so stop workController;
function goOnToDoNextJob() {
clearInterval(workController);
}
// this is just for checking, set var work done after 5 sec
var testWorker = setInterval(function(){ DoJob() }, 5000);
function DoJob()
{
checkWorkDone = true;
clearInterval(testWorker);
}

Related

Redirect with inactivity

My objective is to keep a user in a view as long as he/she keeps clicking a button within a certain lapse.
I'm using Rails and was exploring a solution via an embedded JS in the pertinent view.
So far I'm able to set a time after which the user will be redirected to root path with the following script:
var delayedRedirect = function (){
window.location = "/";
}
var delay = 10000;
$(document).ready(function() {
setTimeout('delayedRedirect()', delay);
});
I've been trying to write a function that resets the value of 'delay'or that calls the setTimeoutFunction again.
$('#btn-persist').click(function() {
delay = 3000;
// or calling again setTimeout('delayedRedirect()', delay);
});
But I noticed that changing the variable won't affect the setTimeout function that has already been called.
I've also tried to use the clearTimeout function as below without success
var delayedRedirect = function (){
window.location = "/persists";
}
var delay = 3000;
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
var stopRedirect = function (){
clearTimeout(triggerRedirect);
}
$(document).ready(function() {
triggerRedirect();
$('#btn-persist').click(function() {
stopRedirect();
});
});
I wonder why this may not be working and if there's any other way to stop the execution of the setTimeout function that has already been called so I can call it again to effectively reset the time to the original value of 'delay'.
At the same time, I don't want to stop any other JS functions that are running in parallel.
Do you see a better solution to achieve this?
The main problem why clearTimeout is not working. because you are clearing a anonymous function instead of a setTimeout variable
change this
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
to this
var triggerRedirect = setTimeout('delayedRedirect()', delay);
Edit:
also change this (if you want to restart the inactive redirect trigger)
$('#btn-persist').click(function() {
stopRedirect();
});
to this
$('#btn-persist').click(function() {
stopRedirect();
triggerRedirect();
});

setInterval not allow simultaneous click event - javascript

I have polling question for you. I am polling information every 20 seconds using setInterval, and have click events that when fired, they pass objects to a method. The problem comes when I click on a button and the event fires at the same time the poll restarts. If that happens, the object that is passed is undefined, which makes sense because when we restart the poll, the information is refreshed. So the question is, how/can one "block" an event from firing when a setInterval is restarting?
Thanks
Going to show some dummy code to illustrate the idea of a queue while you refresh the data on the page:
$(function() {
var isRefreshing = true;
var queue = [];
setInterval(function() {
isRefreshing = true;
$.ajax({
/*
settings
*/
success: function() {
isRefreshing = false;
//process queue
var item;
while(item = queue.pop()) {//if order matters use shift
worker(item);
}
}
});
}, 20*1000);
var worker = function(/*params*/) {
//stuff
}
$("#my-element").click(function() {
var data = {};
if(isRefreshing) {
queue.push(data)
} else {
worker(data);
}
});
});

javascript firing custom event for chrome

can you give me an example for chrome where i have something like this:
function checkVideoStatus(vidElement){
var currentTime = vidElement.currentTime;
//now wait 5 seconds
var updatedTime = vidElement.currentTime;
//now check if video has freezed
if(updatedTime == currentTime){
//fire videoFreeze Event
}
}
So i would want to fire this event here. Also, is it really necessary to fire this event, since i alredy can put a relevant method call here to do what i want accordingly??
Is it in JS the events are only like onChange, onMouseOver etc??
This is a simple mockup of a custom event and a countdown.
<div id="vid" data-current="0">Video</div>​
var vid = document.getElementById('vid'),
freeze;
vid.addEventListener('freeze', function() {
console.log('Firing vid.freeze.... ' + this.dataset.current);
console.log('vid.freeze fired.');
});
(function go() {
var status;
vid.innerHTML = 'Video time: ' + vid.dataset.current;
if (vid.dataset.current < 5) {
status = vid.dataset.current == 0 ? 'Starting... ' : 'Continuing... ';
console.log(status + vid.dataset.current);
setTimeout(go, 1000);
} else {
freeze = document.createEvent('CustomEvent');
freeze.initEvent('freeze', true, true);
vid.dispatchEvent(freeze);
}
vid.dataset.current++;
})();​
http://jsfiddle.net/userdude/Ampbm/1
This is mostly to show how to make a custom event which fires after five seconds. I'm also using the data- attribute to store the current time. What you're doing in the if block I'm not quite sure about, since .updatedTime and .currentTime seems to me to be possibly the same thing each go round.

Using timers (onload)

Ok, firstly, I hardly know Javascript. I really don't know what I'm doing.
So, I have this code:
var interval_id = 0;
var prevent_bust = 0;
// Event handler to catch execution of the busting script.
window.onbeforeunload = function() { prevent_bust++ };
// Continuously monitor whether busting script has fired.
interval_id = setInterval(function() {
if (prevent_bust > 0) { // Yes: it has fired.
prevent_bust -= 2; // Avoid further action.
// Get a 'No Content' status which keeps us on the same page.
window.top.location = 'http://vadremix.com/204.php';
}
}, 1);
function clear ()
{
clearInterval(interval_id);
}
window.onload="setTimeout(clear (), 1000)";
After 1 second I want to clear the interval set earlier. This isn't working. How would I do what I'm trying to do?
If you substitute the last line with window.onload = function() { setTimeout(clear, 1000); }, it should do OK.
There are two errors in your code:
window.onload should be a function, rather than a string ("..."),
setTimeout accepts a function (clear), rather than the result from the function (clear())
By the way, these are some good places to learn JavaScript:
QuirksMode
Mozilla Developer Network

How can I execute a setTimeout() only when the user is present (with the mouse movement) with jQuery

I have a function that updates a <div /> via AJAX:
function update() {
<!-- .ajax() -->
setTimeout(update(), 3000);}
}
What I need is that this is not executed when the user is not present on the website, so if there is no movement of the mouse (we will suppose that if move it is in the website) it will not update .mousemove(). By the way, there is any other thing that we can do to know is someone is active on the website?
How can this be done? Thank you in advance!
Edit: probably I explained bad. I need to know the way to only update when there is activity. Like Facebook does with his news feed, the front page. Thanks!
You could use a mousemove handler to track when the user last moved, and then have the process only happen if they last moved the mouse within X seconds. But of course, if the user is sitting there reading something, or if they're a keyboard-oriented kind of person, that will tend to miss that they are there... So you'd probably want to look at keydown as well.
Here's a mousemove example:
jQuery(function($) {
var count = 0, lastmove = new Date();
$(document).mousemove(function() {
++count;
lastmove = new Date();
$('#display').html("Moved " + count + " times");
});
});​
Then your update code could do this:
function update() {
if (new Date() - lastmove < 60000) { // 60 seconds
// Really do the update
}
else {
// Check back in a few seconds
setTimeout(update, 3000);
}
}
Off-topic, but you have an error in your update code. You have:
setTimeout(update(), 3000);
...which will call update immediately and then try to use its return value to schedule something to happen in three seconds. If you want the call to update to be scheduled to happen in three seconds, leave off the () after it:
setTimeout(update, 3000);
I think I might have ended up with something such as this. Avoids date arithmetic. Only cares whether there's been some activity since the last update().
window.activeFlag = false;
window.updateDelay = 3000;
$(document).bind('mousemove scroll keydown', function(){ activeFlag = true; });
function update() {
if(activeFlag) {
doWork();
activeFlag = false;
}
}
window.setTimeout(update, updateDelay);
edit: I've discovered a flaw in the code. The following is more appropriate:
window.activeFlag = false;
window.updateDelay = 3000;
$(document).bind('mousemove scroll keydown', function(){ activeFlag = true; });
function update() {
if(activeFlag) {
doWork();
activeFlag = false;
}
window.setTimeout(update, updateDelay);
}
update();
I think there is no easy way to determine if the user is present
I would use a combination of mousemove, scroll, keypress.
var bUpdate = false;
function update() {
if(bUpdate){
///perform your ajax request
}
}
$(document).mousemove(function(){
bUpdate = true;
setTimeout(function(){bUpdate=false;}, 3000);}
});

Categories

Resources