I am trying to put a timer on an open case. I put this on my button
<input type="submit" value="Checkout" name="submitAction" class="btn btn-block alert-success" onclick="unlockcase()" />
Here is my function that calls my controller and closes the case after 15 minutes.
function unlockcase() {
setTimeout(function () {
var id = @Model.ID
$.ajax({
type: 'POST',
url: '/Case/UnlockCase',
data: 'id=' + id,
success: function () {
window.location.reload(true);
}
});
},15000);
};
It hits the function and the controller but it happens immediately without the timer working. Any help would be greatly appreciated.
First of all change your html
to this
<button type="button" class="btn btn-block alert-success" onclick="unlockcase()">Checkout</button>
Then your javascript
can be as followes
function unlockcase() {
setTimeout(function () {
var id = @Model.ID;
$.ajax({
type: 'POST',
url: '/Case/UnlockCase',
data: 'id=' + id,
success: function () {
window.location.reload(true);
}
});
}, 15 * 1000 * 60);
}
The unit of waiting period in setTimeoout
is millisecond
so 15 * 1000
means 15 seconds and 15 * 1000 * 60
means 15 minutes.
If you're using jQuery why not use the .click()
event on the button. Something like this:
HTML:
<input type="submit" value="Checkout" name="submitAction" class="btn btn-block alert-success myButton" />
Javascript:
$('.myButton').click(function() {
var counter = 1;
var timer = setInterval(function(){
if(counter > 900000){ //If it passed 15 minutes.
//DO YOUR AJAX CALL
var id = @Model.ID;
$.ajax({
type: 'POST',
url: '/Case/UnlockCase',
data: 'id=' + id,
success: function () {
window.location.reload(true);
}
});
//Clear the loop
clearInterval(timer);
}
counter++;
}, 1000);
});
JSFiddle: http://jsfiddle.net/hoggen1o/