Creating a delayed search with a delay reset - javascript

I have a search function that I need to fire about 2 seconds after the user stops typing in a search bar (which then filters entries of a table). If the user types or otherwise edits the contents of the search bar within those 2 seconds, the timer resets back to 2 seconds before the search request fires.
If I need to, I will post example code of what I have if requested, but I have little idea what should be included at the moment.
Edit: Tags and fact that the project is in Laravel is irrelevant.

This is not a laravel problem but off JavaScript
this should get you started in what you're trying to achieve:
var countDown;
const functionForSearching=()=>{
//do your searching here
}
const delayedSearch() {
clearTimeout(countDown);
countDown = setTimeout(()=>{
//call your search Function Here
functionForSeaching()
},2000);
}

Related

How to code Websockets/AJAX for frequent database updates? Or is there a better method?

I’m making a html & Javascript game and I’m currently trying to write some code that will show the player’s gold balance on the screen and make it decrement by 1 every time the player clicks on a Javascript object (this object is placed in a div on the html page).
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a <div> but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
I don’t want the figure to decrement below 0. Instead, whenever it reaches 0 I want to initiate a Javascript modal to inform the player that they’ve run out of coins.
~~
Originally I was trying to use websockets to display the player’s balance on screen, but I found it very confusing (I’m a beginner at programming in general), so I’m now trying to load the balance on page load, then post the updated balance amount back to my database using AJAX every 60 seconds, or whenever the user closes the browser window, refreshes the page or navigates away from the page. I don’t know if it’s possible to do all these things, or where to start, maybe this is a really bad way to go about this and maybe it's not scalable (maybe the database wouldn't support constant updates from 1000s of players by using this method)?
I would really appreciate any advice or help anyone could give me on any of this.
Thanks in advance!
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
Here are two divs: you store the total number of coins in one and you click the second one to lose coins
<div id="coins">10</div>
<div onCLick="javascript:loseCoin()">If you click here it will cost you 1 coin</div>
Using a function to decrement the cost.
function loseCoin(){
var coins = getElementByid("coins");
var coins_nr = parseInt(coins.innerHTML,10);
if( coins_nr> 0 ){
coins.innerHTML = coins_nr - 1;
} else {
showModal();
}
}
Where showModal() will be your modal (ask if you don't know how to make it)
As for updating the database every 60 sec, you would need a timer loop such as:
setInterval(function () {
// get number of coins from your div's innerHTML
// then call your ajax controller to update DB
}, 60000);
An example of ajax using javascript:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE ) {
if(xhr.status == 200){
console.log(xhr.responseText);
} else {
console.log('something else other than 200 was returned');
}
}
}
xhr.open("POST", "url_of_your_controller_here", true);
xhr.send("coins="+ coins_nr);
(maybe the database wouldn't support constant updates from 1000s of
players by using this method)?
Any decent server should have no problem handling 1000 requests every 60 sec, but it may depend on how many other requests it has and the complexity of your requests.
If you are just trying to decrement a visible counter in the window on each click, you can do something like this:
HTML:
<div id="coinsRemaining">20</div>
code:
// use whatever click handler is appropriate to your app
document.addEventListener("click", function(e) {
var elem = document.getElementById("coinsRemaining");
// get current display text and convert to number
var cnt = +elem.textContent;
--cnt;
if (cnt >= 0) {
elem.textContent = cnt;
}
if (cnt <= 0) {
alert("There are no more coins");
}
});
Working demo: http://jsfiddle.net/jfriend00/s9jb6uhf/
It seems like you don't need to update the database on every click unless there's some realtime aspect of your coin balance that affects other users. If you're just keeping track of your coin balance for future web page visits, then you could update the database much less often than every click.

Continuously Add | Update | Refresh data from database to a page without post back

After a new data has been inserted into database, I want the page which is used to display the data from database to be refreshed/updated and show the new data automatically without hitting the refresh button (like in Facebook feed page, or right here in stackoverflow.com, when new answer posted, it shows an alert of that answer immediately)
What techniques I should use to archive that?
There is a function in JavaScript called setInterval that takes two arguments: a function to execute, and an interval in milliseconds with which the function is run. So, you can have a function called update that fetches all the new data and appends it to your tables, and pass it to setInterval to continuously execute. To run an update function every 5 seconds, you can do something like this:
function update() {
//fetch new data using AJAX and update tables
}
setInterval(update, 5000);
For make the page add new row to waiting customer table automatically
You have to make an ajax call in every few seconds to check whether any new row added if yes then you have to fetch that row and append it to table.

pdf 3d with JavaScript : simple example

I need to do a simple pdf with some 3D objects for an oral presentation. I made several views, each one with a camera viewpoint, an object and a display mode.
To avoid the need to manually switch between the different viewpoints with the context menu, I would like the viewpoints to switch automatically with a Timer (each viewpoint staying for a few seconds). And I would like to not have to touch the mouse at all (nor the keyboard), so I would like to have the playback started as soon as the page appears.
I found the javascript command runtime.setView(N,x) to switch to the x'th view among N, but I don't know where to put it (I don't want to define a function which will be called when I press a button, since I want everything to be automated). Also, I don't know how to pause for a few seconds.
Any help ? Thanks !
I believe you're looking for setInterval(fn, time) which will call a function periodically at a time interval that you set. I'm not familiar with the setView() method you mentioned, but here's some pseudo code that you would put in tags at the end of the document body.
function startSwitcher()
var viewNum = 0;
var maxViews = 5; // you set this to how many views there are
setInterval(function() {
++viewNum;
if (viewNum >= maxViews) {
viewNum = 0;
}
runtime.setView(N, viewNum); // you will have to figure out this line
}, 2000);
}
startSwitcher();
The 2000 is 2000 milliseconds and is the time interval between executing the function. You can put any number of milliseconds there.
The runtime.setView(N, viewNum) line is something you will have to figure out as I am not familiar with whatever library you're trying to use there. The operative part of this code is the viewNum variable which configures which view in rotation should be next.
I think the runtime.SetView(..) Methods works with the name of the view as a string instead of the viewnumber. I have this function in a Dokument-level script and it works for me:
// view is the name of the view for example "TopView"
function setView(view){
console.println("Navigating to view: "+view);
var pageIndex = this.pageNum;
var annotIndex = 0;
var c3d = this.getAnnots3D( pageIndex )[ annotIndex ].context3D;
c3d.runtime.setView(view, true);
}
Combine this with the setInterval(..) from jfriend00´s answer und you should get what you need.
Best regards

Update the database when timer counts down to zero

I have a countdown timer which uses ajax calls to update itself. Something like
<div class="timer5">--:--:--</div>
I want to call a PHP function (only once) using jQuery which will update the database once the timer goes to 00:00:00.
The thing is, the timer can be increased at any time (it's an auction) so I can't just run a script after X time that will update the DB. I have to call the script when the timer really reaches zero.
How can this be done? Is there a some sort of an event in jQuery for that?
In my experience jquery countdown plugin is good for these things.Using this plugin you can easily do this.
var auction_id = array('1','2','3','4','5') // auction ids in array
jQuery(auction_id).each(function(key, val){
jQuery('.countbox-'+val).countdown({
//other options ref in plugin link
onExpiry: function(){
sold(val); // passing argument
//ajax call goes here to update db
}
});
}
To update your clock, I already answered here. The second part of the answer will be help full for you.
if you want to create multiple auction clock in page.you need to collect all auction ids
in array.then you can create clock for each of auction.
If it's done using AJAX you already get a call to your server, updating the timer and knowing how much time is left. Do the database update there.

How to delay KeyPress function when user is typing, so it doesn't fire a request for each keystroke?

background
I have a number of dropdowns on a page. If you change the first one, the rest of the dropdowns are updated according to what you've selected.
In our case, we deal with fund data. So the first dropdown is "All Fund Types". You select "Hedge Funds", and the next dropdown is filtered by options that only apply to Hedge Funds.
The client is now asking me to put a text field into the mix, which when the user starts typing, will effect those results.
So if they type "USD", the second dropdown will only contain options that have funds with "USD" in the name.
problem
The specific problem that I'm having is that with the code I'm using:
$('#Search').keypress(function () {
// trigger the updating process
});
It's triggering the search for each key press. So when I type "USD" I'm getting 3 requests immediately - one for "U", one for "US" and one for "USD".
I've tried setting a timeout with this:
$('#Search').keypress(function () {
// I figure 2 seconds is enough to type something meaningful
setTimeout(getFilteredResultCount(), 2000);
});
but all that does is wait 2 seconds before doing what I've described.
I'm sure this problem has been solved before. Could somebody suggest how to solve this issue?
The way I have done this before is to set a timeout, but clear the existing timeout each time a new key is pressed. That way you should only get the request being sent when the user has stopped typing.
var timeoutId = 0;
$('#Search').keypress(function () {
clearTimeout(timeoutId); // doesn't matter if it's 0
timeoutId = setTimeout(getFilteredResultCount, 500);
// Note: when passing a function to setTimeout, just pass the function name.
// If you call the function, like: getFilteredResultCount(), it will execute immediately.
});
(I'd go for about 500ms timeout.)

Categories